简体   繁体   English

将键/值添加到数组内的对象

[英]Add key/value to an object inside an array

How can i add a key+value to each object in my array. 如何将键+值添加到数组中的每个对象。 Do i have to make a loop or is there a simple method to do that? 我必须进行循环还是有一种简单的方法来做到这一点?

What i have : 我有的 :

 var tab = []; tab.push({name: 'Volvo', firstname: 'Doto'}, {name: 'Velve', firstname: 'Dete'}); 

What i need is to add a property image for each object inside the tab array. 我需要为选项卡数组内的每个对象添加一个属性图像。

Like this : 像这样 :

 var tab = []; tab.push({name: 'Volvo', firstname: 'Doto', image: 'Volvoimg'}, {name: 'Velve', firstname: 'Dete', image: 'Velveimg'}); 

尝试

tab = tab.map( function(value){value.image  = value.name + "img"; return value;} )

Map is one way if you wish to return an new array. 如果您希望返回新数组,则Map是一种方法。 gurvinder372 has an answer that shows how to use map. gurvinder372有一个答案 ,显示了如何使用地图。

An alternative is to use a forEach, this however has whats called 'side effects' and probably isn't the best approach. 一种替代方法是使用forEach,但是这有所谓的“副作用”,可能不是最好的方法。 I think the map example is best, but I've included this as a matter of completeness. 我认为地图示例是最好的,但出于完整性考虑,我已将其包括在内。

tab.forEach((obj) => obj.image = "whatever goes here");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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