Javascript 如何在javascript中动态地向对象数组添加值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7858385/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 03:51:36  来源:igfitidea点击:

how to add values to an array of objects dynamically in javascript?

javascriptarrays

提问by Mujtaba Haider

this is an array of objects,

这是一个对象数组,

var data = [
      {"label" : "1", "value" : 12},
      {"label" : "1", "value" : 12},
      {"label" : "1", "value" : 12},
      {"label" : "1", "value" : 12}
    ];

how can i add values to these dynamically? i tried the below code but no success

我如何动态地向这些添加值?我尝试了下面的代码但没有成功

var lab =["1","2","3", "4"];
var val = [42,55,51,22];
var data = new Array();
for(var i=0; i<4; i++){
   data[i].label = lab[i];
   data[i].value = val[i];    
}

anyone please.. thanks in advance

任何人请..提前致谢

回答by Felix Kling

You have to instantiate the object first. The simplest way is:

您必须先实例化对象。最简单的方法是:

var lab =["1","2","3"];
var val = [42,55,51,22];
var data = [];
for(var i=0; i<4; i++)  {
    data.push({label: lab[i], value: val[i]});
}

Or an other, less concise way, but closer to your original code:

或者另一种不太简洁但更接近原始代码的方式:

for(var i=0; i<4; i++)  {
   data[i] = {};              // creates a new object
   data[i].label = lab[i];
   data[i].value = val[i];    
}

array()will not create a new array (unless you defined that function). Either Array()or new Array()or just [].

array()不会创建新数组(除非您定义了该函数)。无论是Array()new Array(),或只是[]

I recommend to read the MDN JavaScript Guide.

我建议阅读MDN JavaScript 指南

回答by its4zahoor

In Year 2019, we can use Javascript's ES6Spread syntaxto do it concisely and efficiently

2019年我们可以使用Javascript的ES6 Spread语法简洁高效

data = [...data, {"label": 2, "value": 13}]

Examples

例子

var data = [
      {"label" : "1", "value" : 12},
      {"label" : "1", "value" : 12},
      {"label" : "1", "value" : 12},
    ];
    
data = [...data, {"label" : "2", "value" : 14}] 
console.log(data)

For your case (i know it was in 2011), we can do it with map()& forEach()like below

对于您的情况(我知道是在 2011 年),我们可以使用map()forEach() 来完成,如下所示

var lab = ["1","2","3","4"];
var val = [42,55,51,22];

//Using forEach()
var data = [];
val.forEach((v,i) => 
   data= [...data, {"label": lab[i], "value":v}]
)

//Using map()
var dataMap = val.map((v,i) => 
 ({"label": lab[i], "value":v})
)

console.log('data: ', data);
console.log('dataMap : ', dataMap);