Is there any way in javascript which can modify array value. I have done it by using for loop and there is another method call forEach. I wanted to get it done by using only one line. Like I have seen code for converting onject into array by using Array.prototype.slice. So can we get the requirement done by using similar function. I google it but did not find any relevant post.
this.gome = (function(data){
for(var i=0;i<data.length;i++){
data[i].id = i
}
return data })(data.gome);
this.gome = Array.prototype.slice.call(data.gome,//code) // something like that.
asked Feb 3, 2016 at 15:13
Jitender
7,99932 gold badges117 silver badges218 bronze badges
2 Answers 2
map is your friend:
this.gome = data.gome.map((x, i) => ({...x, id: i}));
Or without ES2016 :
this.gome = data.gome.map((x, i) => Object.assign({}, x, {id: i }));
answered Feb 3, 2016 at 15:16
Benjamin Gruenbaum
278k90 gold badges524 silver badges524 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
this will add the values with one line, it's still a for loop though
for(var i = 0, l = data.length; i<l; i++){ data[i].id = i };
answered Feb 3, 2016 at 15:30
Fire Crow
7,7894 gold badges38 silver badges35 bronze badges
Comments
lang-js
forEachexactly? Should be perfect here.