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

主宰稳场 提交于 2021-02-19 09:24:53

问题


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!


回答1:


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


来源:https://stackoverflow.com/questions/48672314/modifying-an-array-of-objects-to-group-into-a-nested-parent-child-array-of-obj

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!