将元素添加到数组Javascript

时间:2015-06-10 10:51:42

标签: javascript arrays

我有一个如下所示的数组:

enter image description here

我想添加一个名为“attributes”的新项目,它也是一个数组。我可以这样做吗?

感谢。

2 个答案:

答案 0 :(得分:1)

var test = [{
  enabled: true,
  key: 'FIN28',
  text: 'Service Agreement'
}, {
  enabled: true,
  key: 'test',
  text: 'test test'
}];

for (var i = 0; i < test.length; i++) {
  test[i]['attributes'] = [];
}
console.log(test);

答案 1 :(得分:0)

根据您的评论,您希望将名为“attribute”的属性添加到数组中的对象。你可以这样做:

myarray[0].attribute = myvalue;

如果您想为阵列的每个项目执行此操作,可以执行以下操作:

for(var idx in myarray)
    myarray[idx].attribute = myvalue;