4

I am using following function to add index to each array object but all id get same value when I check console.log

var foo = [...this.props.articleList];
foo.forEach(function(row, index) {
row.id = index+1;
});
console.log(foo);

I want something like this =>

[{…}, {…}, {…}, {…}, id: 1], [{…}, {…}, {…}, {…}, id: 2], [{…}, {…}, {…}, {…}, id: 3]

but it is returning

[{…}, {…}, {…}, {…}, id: 3], [{…}, {…}, {…}, {…}, id: 3], [{…}, {…}, {…}, {…}, id: 3]

2
  • 2
    I'd guess that each object in the array is actually a reference to the same object in memory, can you post more of the code so we have a minimal reproducible example? Commented Oct 26, 2018 at 3:45
  • actually its json data coming from reducer , i want to set in reducer only. in reducer . here is a reducer code case types.SOMETHING: var foo = [...state.List, action.payload] foo.forEach(function(row, index) { row.index = index+1; }); return { ...state,List: foo } Commented Oct 26, 2018 at 3:49

3 Answers 3

1

The problem appears to stem from handling foo and subsequently manipulating row.id in a mutative manner.

The solution is to leverage a strategy commonly referred to as cloning.

Tools such as spread syntax and Array.prototype.map() tend to be useful for this.

See below for a practical example.

case types.SOMETHING: 
    return {...state, List: [...state.List, action.payload].map((row, index) => ({...row, index}))}
Sign up to request clarification or add additional context in comments.

Comments

1

You could user array.map as follows

var foo = [...this.props.articleList];
foo = foo.map(function(row, index) {
row.id = index+1
return row;
});
console.log(foo);

Comments

1

Try this. The below two solutions would work

     const foo = [...this.props.articleList];
     const articles = foo.map((row, index) => (
             row.id = index+1;
     ));
    console.log(articles);

Or

     const foo = [...this.props.articleList];
     const articles = foo.map((row, index) => {
            return row.id = index+1;
     });
    console.log(articles);

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.