teddym
teddym

Reputation: 55

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'});

Upvotes: 1

Views: 3911

Answers (2)

NMunro
NMunro

Reputation: 910

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");

Upvotes: 2

gurvinder372
gurvinder372

Reputation: 68383

try

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

Upvotes: 5

Related Questions