gpt4 book ai didi

javascript - 对嵌套数组进行分组

转载 作者:行者123 更新时间:2023-11-29 17:00:51 26 4
gpt4 key购买 nike

Fiddle Example

我有一个由 d3.js 中的 nest 方法生成的数组 任何人都可以建议一种 javascript/jQuery 方法来对 values 中的对象进行分组> 按类别划分的属性?

var data = [
{
"key": "0",
"values": [
{
"category": "phone",
"brand": "Sony",
"brand_id": "0",
"name": "item A",
"id": "551",
"point": "600"
},
{
"category": "software",
"brand": "Sony",
"brand_id": "0",
"name": "item D",
"id": "51",
"point": "800"
},
{
"category": "phone",
"brand": "Sony",
"brand_id": "0",
"name": "item E",
"id": "52",
"point": "1800"
}
]
},
{
"key": "0",
"values": [
{
"category": "software",
"brand": "Microsoft",
"brand_id": "1",
"name": "item B",
"id": "54",
"point": "800"
},
{
"category": "phone",
"brand": "Microsoft",
"brand_id": "1",
"name": "item B",
"id": "60",
"point": "200"
},
{
"category": "phone",
"brand": "Microsoft",
"brand_id": "1",
"name": "item T",
"id": "30",
"point": "600"
},
{
"category": "software",
"brand": "Microsoft",
"brand_id": "1",
"name": "item N",
"id": "90",
"point": "500"
}
]
}
];

这是一个理想的结果:

[
{
"key": "0",
"values": [
{
"phone": [
{
"category": "phone",
"brand": "Sony",
"brand_id": "0",
"name": "item A",
"id": "551",
"point": "600"
},
{
"category": "phone",
"brand": "Sony",
"brand_id": "0",
"name": "item E",
"id": "52",
"point": "1800"
}
],
"software": [
{
"category": "software",
"brand": "Sony",
"brand_id": "0",
"name": "item D",
"id": "51",
"point": "800"
}
]
}
]
},
{
"key": "0",
"values": [
{
"phone": [
{
"category": "phone",
"brand": "Microsoft",
"brand_id": "0",
"name": "item B",
"id": "80",
"point": "54"
},
{
"category": "phone",
"brand": "Microsoft",
"brand_id": "0",
"name": "item D",
"id": "52",
"point": "1800"
}
],
"software": [
{
"category": "software",
"brand": "Microsoft",
"brand_id": "0",
"name": "item G",
"id": "41",
"point": "800"
},
{
"category": "software",
"brand": "Microsoft",
"brand_id": "0",
"name": "item L",
"id": "42",
"point": "900"
}
]
}
]
}
]

以下代码无效。我猜这是因为 grouped[t.category] ​​= [] 是在每个循环中定义的。前一项将被最后一项覆盖。如果我没有定义它,我会得到一个 grouped[t.category] undefined 错误:

grouped = {};
data.forEach(function(d){
d.values.map(function(t){
grouped[t.category] = [];
grouped[t.category].push({name:t.name,tid:t.id,point:parseInt(t.point)});
})
})

最佳答案

您可以使用 lodash 以这种方式解决它或类似的库

_.map(data, function(x){
return _.assign({}, x, {values: _.groupBy(x.values, 'category')})
})

Fiddle

关于javascript - 对嵌套数组进行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28164666/

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