1

First i set ids as an object

attribute.map((item, index) => {
                    setIds({ ...ids, [index]: item.id })
                })

then i try to push it in an array, but it is only pushing last object

let idsArr = []
Object.keys(ids).map(key => {
            idsArr.push(ids[key])
        })
3
  • 2
    map returns a new array after iterating over the elements so you should be doing that first, and then updating the state, not updating the state on every iteration. Commented Feb 24, 2022 at 6:55
  • 4
    Please do not use .map() for simple array iteration. Use .forEach() or a normal loop to do that. Commented Feb 24, 2022 at 6:56
  • @VLAZ .foreach() workks fine but when i push it in an array, it returns only last object Commented Feb 24, 2022 at 7:19

2 Answers 2

2

one proposal can be to push the map result in array

idsArr.push(...Object.keys(ids).map(key => ids[key]));

Moreover when you set the id if you don't return nothing the map method should not be used.

A loop like foreach is a better choice

map method is used to get a "transformed" array

  attribute.forEach((item, index) => {
       setIds({ ...ids, [index]: item.id })
  })

let idsArr = [];

let ids = {
  'test': 1,
  'test2': 2
};
idsArr.push(...Object.keys(ids).map(key => ids[key]));

console.log(idsArr);

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

2 Comments

thanks for your answer but idsArr.push(...Object.keys(ids).map(key => ids[key])); is only returning last object
I create a snippet to show the expected result you have the two elements (in my sample 1 and 2) in ids
1

Issue

You are enqueueing a bunch of React state updates inside a loop, using a normal update, and as each update is processed by React it uses the same value of ids from the render cycle they were all enqueued in. In other words, each update stomps the previous one and the last state update wins. This is the state value you see on the subsequent render cycle.

Solutions

Use functional state updates to enqueue each update and have each update from the previous state instead of the state from the callback closure.

Example:

attribute.forEach((item, index) => {
  setIds(ids => ({
    ...ids,
    [index]: item.id,
  }))
});

With the correctly updated ids array state, you should be able to iterate and push values into the other array:

const idsArr = [];
Object.keys(ids).map(key => {
  idsArr.push(ids[key]);
});

Or just get the array of values directly:

const idsArr = Object.values(ids);

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.