Nested key value pair grouping into an array

Viewed 400

I have an Object with nested key value pair as:

Products:{
 Clip:{
   today_entry: 0,
   today_sold: 0
 },
 Necklace:
 {
   today_entry: 0,
   today_sold: 2
 }
}

I want to loop through the Objects Clip ad Necklace and group the values as per their inner keys i.e. today_entry, today_sold into the format:

{
 today_entry : [0,0],
 today_sold : [0,2]
}

I tried doing it using Object.entries but since it is nested I'm not able to get the inner keys. Could anyone please help me? Thank you.

3 Answers

You can use reudce:

const products = {
 Clip:{
   today_entry: 0,
   today_sold: 0,
 },
 Necklace:
 {
   today_entry: 0,
   today_sold: 2,
 },
};

const result = Object.keys(products).reduce((ac, key) => ({
 today_entry: [ ...ac.today_entry, products[key].today_entry],
 today_sold: [ ...ac.today_sold, products[key].today_sold],
}), { today_entry: [], today_sold: []});

console.log(result);

In case the order of the values in the arrays are important you should also sort the keys the way you want.

It is possible to use reduce() method to create an object with Object.values() to get values from object:

const result = Object.values(products).reduce((a, c) => {
    for (const key in c) {
       a[key] = a[key] || [];
       a[key].push(c[key]);
    }
    return a;
},{});

An example:

let products  = {
 Clip:{
   today_entry: 0,
   today_sold: 0
 },
 Necklace:
 {
   today_entry: 0,
   today_sold: 2
 }
}

const result = Object.values(products).reduce((a, c) => {
  for (const key in c) {
a[key] = a[key] || [];
a[key].push(c[key]);
  }
  return a;
},{});



console.log(result)

const products = {
 Clip:{
   today_entry: 0,
   today_sold: 0
 },
 Necklace:
 {
   today_entry: 0,
   today_sold: 2
 }
}

const result = {};

for(item in products) {
  for (action in products[item]) {
    result[action]= result[action]||[];
    result[action].push(products[item][action])
  }
}

console.log(result)
//{ today_entry: [ 0, 0 ], today_sold: [ 0, 2 ] }
Related