简体   繁体   中英

Modifying an array of objects to group into a nested parent / child array of objects by keys and values

I'm currently trying to modify an array of objects to break out into a nested array of objects based on grouping the value of a key.

This is an example of the initial data format:

[
    {key: "Toyota", color: "red", cost: 100 },
    {key: "Toyota", color: "green", cost: 200 },
    {key: "Chevrolet", color: "blue", cost: 300 },
    {key: "Honda", color: "yellow", cost: 400 },
    {key: "Datsun", color: "purple", cost: 500 }
]

This is the output I'm trying to put together:

[{
   key: "Toyota", 
   values:  [
    {color: "red", cost: 100 },
    {color: "green", cost: 200 }
  ]
 }, {
   key: "Chevrolet", 
   values:  [
    {color: "blue", cost: 300 }
  ]
 },{
   key: "Honda", 
   values:  [
    {color: "yellow", cost: 400 }
  ]
 },{
   key: "Datsun", 
   values:  [
    {color: "puruple", cost: 500 }
  ]
 }]

So far I've had some success with these solutions (mostly using the _.map + _.groupBy solution in lodash), which is helping to split the data into a parent -> child format. I'm currently still having some trouble with grouping based on values as well as keys. Group array of object nesting some of the keys with specific names

Current data format looks something like:

 [{
   key: "Toyota", 
   values:  [
    {color: "red", cost: 100 },
  ]
 },{
   key: "Toyota", 
   values:  [
    {color: "green", cost: 200 }
  ]
 }, {
   key: "Chevrolet", 
   values:  [
    {color: "blue", cost: 300 }
  ]
 },{
   key: "Honda", 
   values:  [
    {color: "yellow", cost: 400 }
  ]
 },{
   key: "Datsun", 
   values:  [
    {color: "puruple", cost: 500 }
  ]
 }]

Any help would be greatly appreciated. Thank you!

You could use a Map without additional libraries.

(This is my original answer of the referenced question with single nested rerquirement. The question has a nested approach with more then one level depth, which is here not given.)

 var items = [{ key: "Toyota", color: "red", cost: 100 }, { key: "Toyota", color: "green", cost: 200 }, { key: "Chevrolet", color: "blue", cost: 300 }, { key: "Honda", color: "yellow", cost: 400 }, { key: "Datsun", color: "purple", cost: 500 }], map = new Map, result; items.forEach(({ key, color, cost }) => { map.has(key) || map.set(key, { key, values: [] }); map.get(key).values.push({ color, cost }); }); result = [...map.values()]; console.log(result); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM