Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

104
Views
Array.push is pushing only last object in the array

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])
        })
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report

0

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);
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!