1

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.
2
  • 1
    What's wrong with forEach exactly? Should be perfect here. Commented Feb 3, 2016 at 15:14
  • by using slice are you going to only need part of the array Commented Feb 3, 2016 at 15:30

2 Answers 2

1

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 }));
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

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.