简体   繁体   中英

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. gurvinder372 has an answer that shows how to use map.

An alternative is to use a forEach, this however has whats called 'side effects' and probably isn't the best approach. 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");

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