1

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'});
teddym
  • 55
  • 1
  • 7

2 Answers2

5

try

tab = tab.map( function(value){value.image  = value.name + "img"; return value;} )
gurvinder372
  • 66,980
  • 10
  • 72
  • 94
  • Well i think it was a bad example, i'm not trying to add the word "img" to the value, just to add a loop of image to my tab array for each obj – teddym Mar 10 '16 at 14:24
  • @teddym can you share the example of what you are looking for? Since my answer seems to be in synch with your question. – gurvinder372 Mar 10 '16 at 14:27
  • Well i never used map before, i'm reading the doc, i found the solution but thanks man, we learn everyday – teddym Mar 10 '16 at 14:31
2

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");
Community
  • 1
  • 1
NMunro
  • 890
  • 5
  • 20
  • I never used map() before i'll look for it, thanks for your answer this is what i needed even if i knew it was something like this – teddym Mar 10 '16 at 14:29
  • I'd encourage you to research map, even if you don't use it in this example it's still a very powerful function and does solve many problems. Also If you're done with this question please do mark it as answered. Thanks. – NMunro Mar 10 '16 at 14:31