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

255
Views
convert object keys and values in single Array JS?

I have an object that looks like this:

const dataObj =
{"Tom-29":[ 
    { "number": 12, "string": "hi"},
    { "number": 40, "string": "bye"}
]}

I want something like below and result sorted by number

[
   Name:"Tom",
   Age:29,
    [{"number": 12, "string": "hi"},
    {"number": 40, "string": "bye"}]
];

How would i do this ? I tried below approach .

 const arr =Object.entries(dataObj).map(itm=>({...itm,Name:itm[0]}));

Please help me to resolve

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Iterate the dataObj entries with Array.flatMap(), extract the name and age from the key, and then map the values, and add the properties to the original object using array spread:

const dataObj = {"Tom-29":[{"number":12,"string":"hi"},{"number":40,"string":"bye"}]}

const result = Object.entries(dataObj)
  .flatMap(([key, values]) => {
    const [name, age] = key.split('-')
    
    return values.map(v => ({
      name,
      age: +age,
      ...v
    }))
  })
  
console.log(result);

about 4 years ago · Juan Pablo Isaza Report

0

You can use the object key and append it to each of it's children as a name.

    const dataObj =
    {"Tom-29":[ 
        { "number": 12, "string": "hi"},
        { "number": 40, "string": "bye"}
    ]}

    const results = Object
      .keys(dataObj)
      .map(k => { 
        dataObj[k].forEach(i => { 
          i.name = k.split('-')[0]; 
          i.age = k.split('-')[1]; 
        }); 
        return dataObj[k] 
      })
      .flat();

    console.log(results);

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!