Maxim
Maxim

Reputation: 447

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?

Upvotes: 1

Views: 425

Answers (5)

Yuu
Yuu

Reputation: 359

You can try Object.keys(arr) to get all key name:

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

let after = {}
Object.keys(before).map((key) => {
    let data = before[key].map((x) => { 
        x.set = key
        return x
    })
    after[key] = data 
})
console.log(before)
console.log(after)

==========

[UPDATE] Create after without changed before:

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

let after = {}
Object.entries(before).forEach(([key, data]) => {
    after[key] = data.map((before_value) => { 
        return { 
            ...before_value, 
            set: key
          }
    })
})
console.log(before)
console.log(after)

Upvotes: 0

ycluis
ycluis

Reputation: 16

You can use for...in as well

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

for (const key in data) {
  data[key] = data[key].map(item => ({...item, set: key}))
}

console.log(data);

Upvotes: 0

R4ncid
R4ncid

Reputation: 7139

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)

Upvotes: 1

mplungjan
mplungjan

Reputation: 178350

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)

Upvotes: 0

Charchit Kapoor
Charchit Kapoor

Reputation: 9284

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

Upvotes: 0

Related Questions