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

164
Views
How to rearrange array of objects to new array of Objects

I have an array of objects with the same keys, example:

const data = [{name: "firstName", value: "John"},
{name: "lastName", value: "Smith"},
{name: "Number", value: "421-8686"}
]

I however want the values to become the key and values. example:

const data = [{"firstName": "John"},
{"lastName": "Smith"},
{"Number": "421-8686"}]

I tried a few methods, but for some reason or another I fail. My latest attempt is:

   let newData = {}
    arrayData.forEach((item, index) => {
      let key = data.name
      let value = data.value
      newData[index] = { key: value} // this results in {"key": "John"} --> but i want {"firstName": "John"}

});

about 4 years ago · Santiago Trujillo
3 answers
Answer question

0

const data = [{name: "firstName", value: "John"},
{name: "lastName", value: "Smith"},
{name: "Number", value: "421-8686"}
]


/*const data = [{"firstName": "John"},
{"lastName": "Smith"},
{"Number": "421-8686"}]
*/
for(let i = 0;i < data.length;i++){
   
    data[i][data[i].name] = data[i].value  // creates new key value pair
    delete data[i].name                    // deletes old key
    delete data[i].value
    }
    

console.log(data)

about 4 years ago · Santiago Trujillo Report

0

You can use Object.fromEntries.

let data = [
  {name: "firstName", value: "John"},
  {name: "lastName", value: "Smith"},
  {name: "Number", value: "421-8686"}
]

data = data.map(info => Object.fromEntries([[info.name, info.value]]))

console.log(data)

about 4 years ago · Santiago Trujillo Report

0

I believe you should get result as following, what you want. Of course, I confirmed status.

const data = [{name: "firstName", value: "John"},
{name: "lastName", value: "Smith"},
{name: "Number", value: "421-8686"}
]

let newData = [];
data.forEach((item) => {
  let obj = {};
  obj[item.name] = item.value;
  newData.push( obj );
});
    
console.log(newData);

Thanks.

about 4 years ago · Santiago Trujillo 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!