使用Javascript从Json文件中删除重复项

时间:2018-06-26 06:05:52

标签: javascript arrays json duplicates

我有一个像下面的json文件(test.json)。我尝试解析测试数组并删除下面任何“名称”的重复项均未成功

      {
    "test": [{
            "name": "jeb",
            "occupation": "teacher"
        },

        {
            "name": "jeb",
            "occupation": "writer"
        },
        {
            "name": "bob",
            "occupation": "skydiver"
        }

    ]
}

到目前为止,我的代码如下:

var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        var myObj = JSON.parse(this.responseText);
        var i;
        var test= myObj.test.length;

        for (i=0; i<=myObj.test.length; i++) {
          var name = myObj.test[i].name;
          var occupation = myObj.test[i].occupation;
          console.log(name + " and " + occupation)

        }
      }
}
xmlhttp.open("GET", "test.json", true);
xmlhttp.send();

并打印出来:

jeb and teacher
jeb and writer
bob and skydiver

我希望最终结果是:

jeb and teacher, writer
bob and skydiver

感谢您的帮助。谢谢!

1 个答案:

答案 0 :(得分:3)

最好将reduce放入由name索引的对象中,该对象的值是一个职业数组,然后在创建该对象之后,可以对其进行迭代并打印职业每个名字的:

const obj = {
  "test": [{
    "name": "jeb",
    "occupation": "teacher"
  },{
    "name": "jeb",
    "occupation": "writer"
  },{
    "name": "bob",
    "occupation": "skydiver"
  }]
};

const namesByOccupation = obj.test.reduce((a, { name, occupation }) => {
  if (!a[name]) a[name] = [];
  a[name].push(occupation);
  return a;
}, {});
Object.entries(namesByOccupation).forEach(([name, occupations]) => {
  console.log(name + ' and ' + occupations.join(', '));
});