如何过滤具有相同ID的JSON数组?

时间:2018-02-06 08:38:00

标签: javascript arrays json

我的JSON数据如下:

{
  "Data":
    [
      {"ID": A1,"Function": A,"Status": 1},
      {"ID": A1,"Function": B,"Status": 0},
      {"ID": A1,"Function": C,"Status": 1},
      {"ID": A2,"Function": A,"Status": 0},
      {"ID": A2,"Function": B,"Status": 0},
      {"ID": A2,"Function": C,"Status": 2},
      {"ID": A3,"Function": A,"Status": 0},
      {"ID": A3,"Function": B,"Status": 0}
    ]
}

这就是我想要的:

{
  "Data":
    [
      {"ID": A1,"Status": 1},
      {"ID": A2,"Status": 2},
      {"ID": A3,"Status": 0}
    ]
}

我有很多重复的ID,而我只需要一个ID最多的ID。 我只是不知道从哪里开始。谁能给我一些提示?

2 个答案:

答案 0 :(得分:1)

您可以使用Map作为对具有相同ID的结果数组索引的引用,并检查实际Status是否更小,然后更新数组。



var data = [{ ID: 'A1', Status: 1 }, { ID: 'A1', Status: 0 }, { ID: 'A1', Status: 1 }, { ID: 'A2', Status: 0 }, { ID: 'A2', Status: 0 }, { ID: 'A2', Status: 2 }, { ID: 'A3', Status: 0 }, { ID: 'A3', Status: 0 }],
    map = new Map,
    filtered = [];

data.forEach(function (o) {
    var index = map.get(o.ID);               // get index
    if (index === undefined) {               // if no index available
        map.set(o.ID, filtered.push(o) - 1); // push object and store index in map
        return;                              // exit early
    }
    if (filtered[index].Status < o.Status) { // check status
        filtered[index] = o;                 // update array
    }
});

console.log(filtered);
&#13;
.as-console-wrapper { max-height: 100% !important; top: 0; }
&#13;
&#13;
&#13;

没有Map

&#13;
&#13;
var data = [{ ID: 'A1', Status: 1 }, { ID: 'A1', Status: 0 }, { ID: 'A1', Status: 1 }, { ID: 'A2', Status: 0 }, { ID: 'A2', Status: 0 }, { ID: 'A2', Status: 2 }, { ID: 'A3', Status: 0 }, { ID: 'A3', Status: 0 }],
    filtered = data.reduce(function (r, o) {
        var index = r.findIndex(({ ID }) => ID === o.ID);
        if (index === -1) {
            r.push(o);
            return r;
        }
        if (r[index].Status < o.Status) {
            r[index] = o;
        }
        return r;
    }, []);

console.log(filtered);
&#13;
.as-console-wrapper { max-height: 100% !important; top: 0; }
&#13;
&#13;
&#13;

答案 1 :(得分:1)

您可以使用array#reduce并使用IDStatus创建对象,如果值小于存储值,则替换Status的值。使用Object#values()从对象中提取所有值。

var data = { "Data": [ {"ID": "A1","Function": "A","Status": 1}, {"ID": "A1","Function": "B","Status": 0}, {"ID": "A1","Function": "C","Status": 1}, {"ID": "A2","Function": "A","Status": 0}, {"ID": "A2","Function": "B","Status": 0}, {"ID": "A2","Function": "C","Status": 2}, {"ID": "A3","Function":"A","Status": 0}, {"ID": "A3","Function": "B","Status": 0} ] },
    result = Object.values(data.Data.reduce((r,{ID, Status}) => {
      if(ID in r ) {
        if (r[ID].Status < Status)
          r[ID].Status = Status;
      } else {
        r[ID] = {ID, Status};
      }
      return r;
    },{}));
var output = {Data: result};
console.log(output);