So I have the following JSON. The result that I'm looking for is if there are multiple objects with the same site_id, to create an object which contains the site_id, an array of users, and the rest of the properties merged together. I tried using reduce, but it's not working :D
所以我有以下JSON。我正在寻找的结果是,如果有多个具有相同site_id的对象,则创建一个包含site_id的对象,一组用户,并将其余属性合并在一起。我尝试使用reduce,但它不起作用:D
Thank you in advance
先感谢您
{
"response": [
{
"site_id": "4587c4183c312dd82309be6cdae7bbd6",
"name": "esse",
"lat": 82.3172,
"lon": -30.0668,
"company": "256090f4d3a41f34096876b71ee03694",
"user_id": "2d3393051386426adca86c13362e6f46",
"UserName": "Juliet44",
"Password": "Test",
"FirstName": "Kristy",
"LastName": "Goldner",
"Company": "256090f4d3a41f34096876b71ee03694",
"Email": "Kassandra37@hotmail.com",
},
{
"site_id": "4587c4183c312dd82309be6cdae7bbd6",
"lat": 82.3172,
"lon": -30.0668,
"company": "256090f4d3a41f34096876b71ee03694",
"user_id": "2f2a174f63f7e277630eb808974dfd05",
"UserName": "Marguerite_Smith34",
"Password": "Test",
"FirstName": "Christian",
"LastName": "Gerhold",
"Company": "256090f4d3a41f34096876b71ee03694",
"Email": "Urban.Boyer@yahoo.com",
},
{
"site_id": "94fc61eee3c0d01abace7a2feb84bc4c",
"name": "blanditiis",
"lat": 13.3673,
"lon": 54.3085,
"company": "256090f4d3a41f34096876b71ee03694",
"user_id": "3f85f1a435df6c3ca4ac944116515c04",
"UserName": "Tyrell.Schimmel",
"Password": "Test",
"FirstName": "Lucius",
"LastName": "O'Conner",
"Company": "256090f4d3a41f34096876b71ee03694",
"Email": "Eino.Hackett@gmail.com",
},
]
}
1 个解决方案
#1
0
Probably the rest operator is your friend. And im not shure if you really need to reduce, a simple forEach does it:
其余的运营商可能是你的朋友。如果你真的需要减少,我不会感到害羞,一个简单的forEach就是这样做的:
var hash={}, result = [];
response.forEach(function({site_id,...rest}){
if(!hash[site_id]){
result.push(hash[site_id]={site_id});
}
let el = hash[site_id];
for(key in rest){
if(el[key]){
el[key].push(rest[key]);
}else{
el[key] = [rest[key]];
}
}
});
#1
0
Probably the rest operator is your friend. And im not shure if you really need to reduce, a simple forEach does it:
其余的运营商可能是你的朋友。如果你真的需要减少,我不会感到害羞,一个简单的forEach就是这样做的:
var hash={}, result = [];
response.forEach(function({site_id,...rest}){
if(!hash[site_id]){
result.push(hash[site_id]={site_id});
}
let el = hash[site_id];
for(key in rest){
if(el[key]){
el[key].push(rest[key]);
}else{
el[key] = [rest[key]];
}
}
});