Reputation: 107
I've got an array with some objects :
var myArray = [{
'id': 'first',
'value': 'firstValue'
}, {
'id': 'second',
'value': 'secondValue'
}, {
'id': 'third',
'value': 'thirdValue'},
etc.];
I'm trying to add values with a loop so that I have something like this :
var myArray = [{
'id': 'first',
'value': 'firstValue',
'inc1' : 1
}, {
'id': 'second',
'value': 'secondValue'
'inc2' : 2
}, {
'id': 'third',
'value': 'thirdValue'
'inc3' : 3
}];
I know that with mapping
myArray.forEach(function(o, i) {
o.inc = i + 1;
});
I can get the results incremented, but how do I get the names inc1, inc2, inc3...?
Upvotes: 1
Views: 36
Reputation: 386550
You could use bracket notation for the property as property accessor, like
object.property // dot notation object['property'] // bracket notation
var myArray = [{ id: 'first', value: 'firstValue' }, { id: 'second', value: 'secondValue' }, { id: 'third', value: 'thirdValue' }];
myArray.forEach(function (o, i) {
o['inc' + (i + 1)] = i + 1;
//^^^^^^^^^^^^^^^^ use brackets and property as string
});
console.log(myArray);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Upvotes: 4