gpt4 book ai didi

javascript - 修改对象数组以按键和值分组为嵌套的父/子对象数组

转载 作者:行者123 更新时间:2023-11-28 03:43:59 26 4
gpt4 key购买 nike

我目前正在尝试修改一个对象数组,以根据对键的值进行分组来分解为一个嵌套的对象数组。

这是初始数据格式的示例:

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

这是我尝试组合的输出:

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

到目前为止,我在这些解决方案上取得了一些成功(主要是在 lodash 中使用 _.map + _.groupBy 解决方案),这有助于拆分数据转换为父->子格式。目前,我在根据值和键进行分组方面仍然遇到一些问题。 Group array of object nesting some of the keys with specific names

当前数据格式类似于:

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

任何帮助将不胜感激。谢谢!

最佳答案

您可以使用Map无需额外的库。

(这是我对具有单一嵌套需求的引用问题的原始答案。该问题具有超过一级深度的嵌套方法,此处未给出。)

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

关于javascript - 修改对象数组以按键和值分组为嵌套的父/子对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48672314/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com