1

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...?

1
  • 2
    Just curious: Why do you want to add the number to the property name? Commented May 10, 2017 at 12:34

1 Answer 1

4

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; }

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.