0

I want to update a property in each element in my array to be a particular index. However when I try the following:

  static reindexComponentsOnMultiplePages(components) {
    return components.forEach((el, idx) => (el.componentIndex = idx));
  }

I get returned undefined.

My current array is as follows:

components = [ 
               [ {...}, {...}, {...} ], 
               [ {...}, {...}, {...} ] 
             ]

I was expecting each property in each element in my array to be updated. I call the method as follows:

pageComponents = MyService.reindexComponentsOnMultiplePages(pageComponents);
2
  • 1
    Yes, that's expected, the return value of forEach is undefined. What did you expect to get? Commented Mar 4, 2020 at 8:45
  • Do you mean to use .map()? Commented Mar 4, 2020 at 8:46

1 Answer 1

3

Array.forEach() returns undefined as described in the documentation.

There's no need to return the array, you are updating the items in your forEach loop.

var arr = [{name: 'A', componentIndex: null}, {name: 'B', componentIndex: null}];
console.log(arr);

arr.forEach(function(item, index) {
  item.componentIndex = index;
});

console.log(arr);

Just avoid returning anything, you don't need to.

Sign up to request clarification or add additional context in comments.

2 Comments

Hi my array structure is as follows components = [ [ {...}, {...}, {...} ], [ {...}, {...}, {...} ] ] - basically an array of objects within an array of arrays.
And what is componentIndex to you? Imagine [[A, B], [C, D]] do you want you indices to be [[0, 1], [0, 1]] or [[0, 1], [2, 3]] ?

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.