gpt4 book ai didi

javascript - 映射/组织 Node 中的嵌套对象

转载 作者:行者123 更新时间:2023-12-01 03:55:07 24 4
gpt4 key购买 nike

我正在尝试自己映射嵌套对象,而不使用类似 JoinJS 的东西,这在一定程度上非常有效,直到我想正确地使我的 JSON 看起来很漂亮。

根据 SQL 查询,我的输出是:

[
{
"id": 1,
"city_name": "city 1 - some city name",
"city_category": "city 1 - some category",
"city_description": "city 1 - some city description",
"city_id": 1,
"store_id": 1
},
{
"id": 1,
"city_name": "city 1 - some city name",
"city_category": "city 1 - some category",
"city_description": "city 1 - some city description",
"city_id": 1,
"store_id": 2
},
{
"id": 1,
"city_name": "city 1 - some city name",
"city_category": "city 1 - some category",
"city_description": "city 1 - some city description",
"city_id": 1,
"store_id": 3
},
{
"id": 2,
"city_name": "city 2 - some city name",
"city_category": "city 2 - some category",
"city_description": "city 2 - some city description",
"city_id": 2,
"store_id": 1
},
{
"id": 2,
"city_name": "city 2 - some city name",
"city_category": "city 2 - some category",
"city_description": "city 2 - some city description",
"city_id": 2,
"store_id": 2
}
]

我试图让这个输出看起来像这样:

[
{
"city_id": 1,
"city_name": "city 1 - some city name",
"city_category": "city 1 - some category",
"city_description": "city 1 - some city description",
"store_ids": [1,2,3]
}
{
"city_id": 2,
"city_name": "city 2 - some city name",
"city_category": "city 2 - some category",
"city_description": "city 2 - some city description",
"store_ids": [1,2]
}
]

我的第一个猜测是我需要使用 _.chain(result).uniqBy(' 查找所有唯一的 idcity_id city_id').value()。但后来我有点坚持从输出中删除 id ,最重要的是,如何创建一个新的键 store_ids ,其中包含每个城市所有商店的数组。有道理吗?

使用Lodash或者只是普通的 JS(没有像 JoinJS 这样的其他模块,除非它们对于这样的事情是有效的),我将如何操纵它?

最佳答案

我将运行结果,并将它们分组到我的新对象结果中。最后你将得到一个对象的对象,其键是item.id,但如果你想将它转换为数组,这很简单。

let resultsObject = {};

sqlQueryRows.map(function(item) {
if (item.id in resultsObject) {
resultsObject[item.id].store_ids.push(item.store_id);
} else {
resultsObject[item.id] = {
city_id: item.city_id,
city_name: item.city_name,
city_category: item.city_category,
city_description: item.city_description,
store_ids: [item.store_id]
}
}
});

// if you need an array
let resultsArray = Object.values(resultsObject);

关于javascript - 映射/组织 Node 中的嵌套对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42835176/

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