Nistha Adhikari
Nistha Adhikari

Reputation: 147

Nested key value pair grouping into an array

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.

Upvotes: 2

Views: 630

Answers (3)

Shabir Hamid
Shabir Hamid

Reputation: 148

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 ] }

Upvotes: 1

StepUp
StepUp

Reputation: 38154

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)

Upvotes: 3

Mehran Hatami
Mehran Hatami

Reputation: 12961

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.

Upvotes: 4

Related Questions