Add property to each object in the array

后端 未结 3 1280
执念已碎
执念已碎 2021-01-25 04:04

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         


        
相关标签:
3条回答
  • 2021-01-25 04:37

    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;
    }
    
    0 讨论(0)
  • 2021-01-25 04:38
    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)
    
    0 讨论(0)
  • 2021-01-25 04:47

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

    0 讨论(0)
提交回复
热议问题