我有一个要求,我要在雅典娜中查询并在邮递员中获取这样的api响应:
{
"id": "768ch23sgcjh",
"gpsdate": "2019-04-06T13:02:08",
"val1": "0.36233",
"val2": "344",
"loc": "{latitude=35.8374501, longitude=-49.0303646}"
},
{
"id": "768ch23sgcjh",
"gpsdate": "2019-04-06T13:02:08",
"val1": ".22",
"val2": "145",
"loc": "{latitude=35.8374501, longitude=-49.0303646}"
},
{
"id": "2453hsgdshgc",
"gpsdate": "2019-04-06T13:02:08",
"val1": "0.3030",
"val2": "346",
"loc": "{latitude=35.8374501, longitude=-79.0303646}"
},
我想在框架中做一些喜欢的:
{
"768ch23sgcjh" : [
{
"gpsdate":"2019-04-06T13:02:08",
"val1": "0.36233",
"val2": "344",
"loc": "{latitude=35.8374501, longitude=-49.0303646}"
}
{
"gpsdate":"2019-04-06T13:02:08",
"val1": ".22",
"val2": "145",
"loc": "{latitude=35.8374501, longitude=-49.0303646}"
}
]
"2453hsgdshgc": [
{
"gpsdate":"2019-04-06T13:02:08",
"val1": "0.3030",
"val2": "346",
"loc": "{latitude=35.8374501, longitude=-49.0303646}"
}
]
}
我需要上面的格式。因此,基本上,如果对于给定的ID,有多组项目,则ID应该出现一次。
答案 0 :(得分:1)
let inputArray = [{
"id": "768ch23sgcjh",
"gpsdate": "2019-04-06T13:02:08",
"val1": "0.36233",
"val2": "344",
"loc": "{latitude=35.8374501, longitude=-49.0303646}"
},
{
"id": "768ch23sgcjh",
"gpsdate": "2019-04-06T13:02:08",
"val1": ".22",
"val2": "145",
"loc": "{latitude=35.8374501, longitude=-49.0303646}"
},
{
"id": "2453hsgdshgc",
"gpsdate": "2019-04-06T13:02:08",
"val1": "0.3030",
"val2": "346",
"loc": "{latitude=35.8374501, longitude=-79.0303646}"
}
]
let outputArray = {};
for (let item of inputArray) {
if (!outputArray[item.id]) {
outputArray[item.id] = [{
gpsdate: item.gpsdate,
val1: item.val1,
val2: item.val2,
loc: item.loc
}]
} else {
outputArray[item.id].push({
gpsdate: item.gpsdate,
val1: item.val1,
val2: item.val2,
loc: item.loc
})
}
}
console.log(outputArray);
答案 1 :(得分:0)
您可以使用array#reduce
对基于id
的对象进行分组。
const arr = [{ "id": "768ch23sgcjh", "gpsdate": "2019-04-06T13:02:08", "val1": "0.36233", "val2": "344", "loc": "{latitude=35.8374501, longitude=-49.0303646}" }, { "id": "768ch23sgcjh", "gpsdate": "2019-04-06T13:02:08", "val1": ".22", "val2": "145", "loc": "{latitude=35.8374501,longitude=-49.0303646}" }, { "id": "2453hsgdshgc", "gpsdate": "2019-04-06T13:02:08", "val1": "0.3030", "val2": "346", "loc": "{latitude=35.8374501, longitude=-79.0303646}" }],
result = arr.reduce((r, {id, ...rest}) => {
r[id] = r[id] || [];
r[id].push({...rest});
return r;
},{});
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }