gpt4 book ai didi

JavaScript - 通过相似属性查找对象并将其推送到新数组中

转载 作者:行者123 更新时间:2023-12-04 10:38:49 25 4
gpt4 key购买 nike

我有以下 JSON 树:

[
{
"category":"PASTAS",
"createdAt":"2016-01-01T19:47:57.813Z",
"currency":"$",
"dishName":"Spaghetti",
"estTime":"10-20 min",
"price":10,
"subName":"Pasta",
"updatedAt":"2016-04-28T20:48:06.800Z"
},
{
"category":"PIZZAS",
"createdAt":"2016-04-19T21:44:56.285Z",
"currency":"$",
"dishName":"Ai Funghi Pizza ",
"estTime":"20-30 min",
"price":20,
"subName":"Pizza",
"updatedAt":"2016-04-28T20:58:39.499Z"
},
{
"category":"PIZZAS",
"createdAt":"2016-04-19T21:44:56.285Z",
"currency":"$",
"dishName":"Seafood Pizza",
"estTime":"20-30 min",
"price":10,
"subName":"Pizza",
"updatedAt":"2016-04-28T20:58:39.499Z"
}
]

正如您在 JSON 树中看到的那样,元素 category:"PIZZAS" 重复两次,我想做的是创建一个新数组或以某种方式组织这些结果避免在所有其他重复项中重复,即在上面的示例中,我会得到这样的最终结果:

 Pastas:
Spaghetti

Pizza:
Ai Fungi Pizza,
Seafood Pizza

关于如何实现预期结果的任何想法?

最佳答案

假设数组名为 data,这应该可以解决问题:

var result = {};                                       // Create an output object.
for(var i = 0; i < data.length; i++){ // Loop over the input array.
var row = data[i]; // Store the current row for convenience.
result[row.category] = result[row.category] || []; // Make sure the current category exists on the output.
result[row.category].push(row.dishName); // Add the current dish to the output.
}

关于JavaScript - 通过相似属性查找对象并将其推送到新数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37006138/

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