将属性添加到数组中的每个对象

时间:2016-04-06 11:13:04

标签: javascript arrays object

我试图为数组中的每个对象添加一个属性:

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

应该成为:

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

数组可以包含多个对象。我需要什么样的功能?

3 个答案:

答案 0 :(得分:7)

您必须在此背景下使用forEach

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

如果您不熟悉forEach的用法,那么您可以使用for循环执行相同的工作。

for(var i=0,len=capitals.length;i<len;i++){
  capitals[i].global = true;
}

答案 1 :(得分:0)

如果您不必支持旧版浏览器,则可以使用Array.prototype.map

答案 2 :(得分:0)

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)