简体   繁体   中英

Add property to each object in the array

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?

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

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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM