Add property to each object in the array

若如初见. 提交于 2019-12-31 05:26:06

问题


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?


回答1:


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



回答2:


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




回答3:


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
}];
for(i in capitals) {
  capitals[i].global = true;
}
console.log(capitals)


来源:https://stackoverflow.com/questions/36449456/add-property-to-each-object-in-the-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!