如何在javascript

时间:2017-08-07 16:21:30

标签: javascript arrays sorting object reduce

所以我有以下JSON。我正在寻找的结果是,如果有多个具有相同site_id的对象,则创建一个包含site_id的对象,一组用户,并将其余属性合并在一起。 我尝试使用reduce,但它不起作用:D

提前谢谢

{
        "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 个答案:

答案 0 :(得分:0)

其他运营商可能是你的朋友。如果你真的需要减少,我不会感到害羞,一个简单的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]];
    }
  }
 });