简体   繁体   中英

Using forEach to iterate an array, add to object and use the forEach index for the object key doesn't work

I'm wanting to iterate of an array using forEach , then add the values of that array to an object.

When adding to the object I want to be able to name the object keys with an increasing number, just like when using a normal for loop using the i variable counter.

With the code below:

var myArray = [123, 15, 187, 32];
var testObj = {}
myArray.forEach(function (value, i) {
    console.log('%d: %s', i, value);
    var objectKeyName = "item" + i; // ⬅️ here
    testObj.objectKeyName = value;
});
console.log(testObj);

I would expect testObj to be

{
    item0: 123,
    item1: 15,
    item2: 187,
    item3: 32, 
}

instead it outputs:

{objectKeyName: 32}

Why is this? Any help is greatly appreciated! 😀

The issue is because you're using a variable as the property name. In that situation you cannot use dot notation, and must instead use bracket notation to access the object.

The reason you see only one item in the object currently is because you only set the objectKeyName property, and overwrite it in each iteration of the forEach .

 var myArray = [123, 15, 187, 32]; var testObj = {} myArray.forEach(function(value, i) { var objectKeyName = "item" + i; testObj[objectKeyName] = value; // Note the [] surrounding the variable name here }); console.log(testObj); 

Use testObj[objectKeyName] = value instead of testObj.objectKeyName = value . The dot notation assigns the key value literally.

Here you go with the solution

 var myArray = [123, 15, 187, 32]; var testObj = {} myArray.forEach(function(value, i) { testObj["item" + i] = value; }); console.log(testObj); 

var myArray = [123, 15, 187, 32];
var testObj = [];
myArray.forEach(function (value, i) {
    console.log('%d: %s', i, value);
    var objectKeyName = "item" + i; // ⬅️ here
    testObj.push(objectKeyName + ":" + value);
});
console.log(testObj);
testObj.forEach(function (value, i) {
    console.log(value);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM