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

83
Views
Append object parent key to children

I have the following object given:

{
  "groupA": [
    {data: 'foo'},
    {data: 'bar'}
  ],
  "groupB": [
    {data: 'hi'},
    {data: 'mom'}
  ]
}

I would like to append the parent object keys to all its array items like so:

{
  "groupA": [
    {data: 'foo', set: 'groupA'},
    {data: 'bar', set: 'groupA'}
  ],
  "groupB": [
    {data: 'hi', set: 'groupB'},
    {data: 'mom', set: 'groupB'}
  ]
}

How can I achieve this?

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

0

This is a immutable version that give you a new object using Object.fromEntries Object.entries and map

const data = {
  "groupA": [{
      data: 'foo'
    },
    {
      data: 'bar'
    }
  ],
  "groupB": [{
      data: 'hi'
    },
    {
      data: 'mom'
    }
  ]
}

const withGroup = Object.fromEntries(
     Object.entries(data).map(([set, items]) => [set, items.map(i => ({ ...i,set}))])
)

console.log(withGroup)

about 4 years ago · Juan Pablo Isaza Report

0

You can do it simply by looping over the object and mapping the arrays, like this:

const data = {
  "groupA": [
    {data: 'foo'},
    {data: 'bar'}
  ],
  "groupB": [
    {data: 'hi'},
    {data: 'mom'}
  ]
};

Object.keys(data).forEach(key => {
    data[key] = data[key].map(rec => ({...rec, set: key}));
})

console.log(data);
about 4 years ago · Juan Pablo Isaza Report

0

You can loop and set each item

const obj = {
  "groupA": [
    {data: 'foo'},
    {data: 'bar'}
  ],
  "groupB": [
    {data: 'hi'},
    {data: 'mom'}
  ]
};
Object.entries(obj).forEach(([key,val]) => val.forEach(item => item.set=key))
console.log(obj)

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!