gpt4 book ai didi

javascript - 将数据包装成对象形式

转载 作者:行者123 更新时间:2023-11-28 12:14:01 24 4
gpt4 key购买 nike

我有一个这样的数据集:

[ { city: 'a', value: 1, sector: 'Hospital' },
{ city: 'b', value: 1, sector: 'Hardware' },
{ city: 'c', value: 1, sector: 'Hardware' },
{ city: 'd', value: 1, sector: 'Networking' },
{ city: 'e', value: 1, sector: 'Hospital' },
{ city: 'f', value: 1, sector: 'Education' },
{ city: 'g', value: 1, sector: 'Transport' },
{ city: 'h', value: 1, sector: 'Food' },
{ city: 'i', value: 1, sector: 'Networking' },
{ city: 'j', value: 0.7, sector: 'Software' },
{ city: 'k', value: 0.7, sector: 'Education' },
{ city: 'l', value: 0.7, sector: 'Food' },
{ city: 'm', value: 0.7, sector: 'Hospital' },
{ city: 'n', value: 0.2, sector: 'Networking' },
{ city: 'o', value: 0.2, sector: 'Networking' },
{ city: 'p', value: 0.2, sector: 'Industrial' },
{ city: 'q', value: 0.2, sector: 'Transport' },
{ city: 'r', value: 0.2, sector: 'Software' } ]

现在我想将对象数组转换为数组对象,具有相同扇区重复的城市应该属于特定组。

期望的输出是这样的:

[
{
sector: "Hospital",
place: ["a", "e", "m"]
},
{
sector: "Hardware",
place: ["b", "c"]
},
{
sector: "Networking",
place: ["d", "i", "n", "o"]
},
{
sector: "Education",
place: ["f", "k"]
},
{
sector: "Transport",
place: ["g", "q"]
},
{
sector: "Food",
place: ["h", "l"]
},
{
sector: "Software",
place: ["j", "r"]
},
{
sector: "Industrial",
place: ["q"]
},
]

有没有人建议我如何完成此类任务。非常感谢任何帮助或建议。

我有一个线索,这件事将通过reduce和map函数来完成,但是如何做到这一点将是一个挑战。

我尝试像这样获取扇区重复计数,但没有达到我想要的输出:

let x = data.reduce((m, c) => {
if (c.sector in m) m[c.sector].count += 1;
else m[c.sector] = { sector: c.sector, count: 1 };
return m;
}, {});
console.log(x)

最佳答案

您可以首先提取数组中的所有uniq扇区。

之后映射到每个扇区并过滤您的数据中对应的位置。

var data = [{ city: 'a', value: 1, sector: 'Hospital' },
{ city: 'b', value: 1, sector: 'Hardware' },
{ city: 'c', value: 1, sector: 'Hardware' },
{ city: 'd', value: 1, sector: 'Networking' },
{ city: 'e', value: 1, sector: 'Hospital' },
{ city: 'f', value: 1, sector: 'Education' },
{ city: 'g', value: 1, sector: 'Transport' },
{ city: 'h', value: 1, sector: 'Food' },
{ city: 'i', value: 1, sector: 'Networking' },
{ city: 'j', value: 0.7, sector: 'Software' },
{ city: 'k', value: 0.7, sector: 'Education' },
{ city: 'l', value: 0.7, sector: 'Food' },
{ city: 'm', value: 0.7, sector: 'Hospital' },
{ city: 'n', value: 0.2, sector: 'Networking' },
{ city: 'o', value: 0.2, sector: 'Networking' },
{ city: 'p', value: 0.2, sector: 'Industrial' },
{ city: 'q', value: 0.2, sector: 'Transport' },
{ city: 'r', value: 0.2, sector: 'Software' } ];


var sectors = [];

data.map(d => {
if(sectors.indexOf(d.sector) === -1){
sectors.push(d.sector);
}
})

sectors = sectors.map(sector => {
return {
sector,
places:data.filter(d => d.sector === sector).map(d => d.city)
}
});

console.log(sectors)

关于javascript - 将数据包装成对象形式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53725460/

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