我试图自己映射嵌套对象,而不使用像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]
}
]
我的第一个猜测是,我需要使用id
找到所有唯一的city_id
或_.chain(result).uniqBy('city_id').value()
。但后来我有点卡在从输出中删除id
,最重要的是,如何创建一个具有每个城市所有商店数组的新密钥store_ids
。有意义吗?
使用Lodash或只是简单的JS(没有像JoinJS这样的其他模块,除非它们对这样的事情有效),我将如何操纵它?
答案 0 :(得分:1)
我会浏览结果,并将它们分组到我的新对象结果中。 最后你将得到一个对象的对象,键是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);
答案 1 :(得分:1)
这是我的lodash方法:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="api/reponse-api-2.css">
<link rel="stylesheet" href="css/index.css">
</head>
<body class="nomargin">
<!--MOBILE VERSION-->
<div class="size-small">
<div class="row"><iframe frameBorder="0" src="html/header-small.html" class="col-12" height="100px"/></div>
<div class="row">
<div class="col-12 checkbox-mobile">
<form>
<input type="checkbox">Embed site in browser</input>
</form>
</div>
</div>
</div>
<!--TABLET VERSION-->
<div class="size-medium">
tablet
</div>
<!--PC VERSION-->
<div class="size-large">
pc
</div>
</body>
这个想法是:
答案 2 :(得分:0)
如果你只想删除某些字段,可以使用.map方法,但我不确定我是否完全理解这个问题。
var new_array = array_name.map((val) => {
//do stuff to array
}