2

I'm trying to add a property to each object in the array:

var capitals = [{
    country: "What's the capital of Ecuador?",
    choices: ["Quito", "Caracas", "Panama", "Loja"],
    corAnswer: 0
}, {
    country: "What is the capital of China?",
    choices: ["Shanghai", "Beijing", "Ghangzou", "Hong Kong"],
    corAnswer: 0
}];

Should become:

var capitals = [{
        country: "What's the capital of Ecuador?",
        choices: ["Quito", "Caracas", "Panama", "Loja"],
        corAnswer: 0,
        global: true
    }, {
        country: "What is the capital of China?",
        choices: ["Shanghai", "Beijing", "Ghangzou", "Hong Kong"],
        corAnswer: 0,
        global: true
    }];

The array can contain multiple objects. What kind of function do I need?

0

2 Answers 2

13

You have to use forEach at this context,

capitals.forEach(function(itm){
 itm.global = true;
});

If you are not familiar with the usage of forEach, then you can do the same job by using a for loop.

for(var i=0,len=capitals.length;i<len;i++){
  capitals[i].global = true;
}
Sign up to request clarification or add additional context in comments.

4 Comments

i'd suggest to use .map to not mutate original array of objects
@VladimirStarkov That will create a clone unnecessarily. This context does not require map, I believe.
OP didnt say anything about context, using map provide you explicit data flow instead of implicit one with forEach
const capital = [{}, …].map(i => { i.global = true; return i; }) thats it
-1

If you do not have to support legacy browsers, then you could use Array.prototype.map

1 Comment

Downvoted because you didn't attempt to answer the question. A good answer would show how to use that function in the context of this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.