简体   繁体   English

修改对象数组以通过键和值将其分组为嵌套的父/子对象数组

[英]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. 到目前为止,我已经在这些解决方案上取得了一些成功(主要是在_.map使用_.map + _.groupBy解决方案),这有助于将数据拆分为父级->子级格式。 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. 您可以使用没有其他库的Map

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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