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

2
  • iterate the array and add the property to each of the objects. Commented Mar 10, 2016 at 14:18
  • Something like this : $.each(tab, function(i, field){ field.img = myimage; } ? Is there a better way? Commented Mar 10, 2016 at 14:22

2 Answers 2

5

try

tab = tab.map( function(value){value.image  = value.name + "img"; return value;} )
Sign up to request clarification or add additional context in comments.

3 Comments

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 can you share the example of what you are looking for? Since my answer seems to be in synch with your question.
Well i never used map before, i'm reading the doc, i found the solution but thanks man, we learn everyday
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");

2 Comments

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
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.