如何从Node.js中的JSON对象数组中删除重复项

时间:2018-10-13 01:10:44

标签: node.js

我正在尝试根据以下json的ID删除重复的条目,但是似乎我无法正确解析JSON,我的JSON数组如下:

[ '{"entries":[{"name":"sample","id":"8d"},{"name":"sample","id":"57"},{"name":"sample","id":"acc"}]}\n',
  '{"entries":[{"name":"sample","id":"8d"},{"name":"sample","id":"50"},{"name":"sample","id":"ac"}]}\n',
  '{"entries":[{"name":"sample","id":"8d"},{"name":"sample","id":"50"},{"name":"sample","id":"ac"}]}\n',
  '{"entries":[{"name":"sample","id":"8d"},{"name":"sample","id":"50"}]}\n',
]

输出应为

{"entries":[{"name":"sample","id":"8d"},{"name":"sample","id":"57"},{"name":"sample","id":"acc"}]}

我的代码如下:

removeDups: async function(listent){
      for (i = 0; i < listent.length; i++){
        console.log(listent.length)
         for (j = 0; j < listent.length; j++){
           console.log(listent[j])
       }
        var standardsList = this.arrUnique(listent);
        console.log("standard", standardsList)
    }
    },

    arrUnique: function (arr) {
      var cleaned = [];
      arr.forEach(function(itm) {
          var unique = true;
          cleaned.forEach(function(itm2) {
              if (_.isEqual(itm, itm2)) unique = false;
          });
          if (unique)  cleaned.push(itm);
      });
      return cleaned;

      }

2 个答案:

答案 0 :(得分:1)

希望这对您有用:https://jsfiddle.net/c0pkw5ju/

核心功能是:

var val = array.reduce(function (acc, val) {
    return acc.concat(val.entries)
}, [])

console.log(_.unique(val, function (v) {
    return v.id
}))

基本上,您需要将\n分隔的JSON响应转换为JS对象,该对象可以按指示使用。让我知道这是否没有帮助。

输出:

[
  {
    "name": "sample",
    "id": "8d"
  },
  {
    "name": "sample",
    "id": "57"
  },
  {
    "name": "sample",
    "id": "acc"
  },
  {
    "name": "sample",
    "id": "50"
  },
  {
    "name": "sample",
    "id": "ac"
  }
]

更新: 假设响应为:

var response = ['{"entries":[{"name":"sample","id":"8d"},{"name":"sample","id":"57"},{"name":"sample","id":"acc"}]}\n',
    '{"entries":[{"name":"sample","id":"8d"},{"name":"sample","id":"50"},{"name":"sample","id":"ac"}]}\n',
    '{"entries":[{"name":"sample","id":"8d"},{"name":"sample","id":"50"},{"name":"sample","id":"ac"}]}\n',
    '{"entries":[{"name":"sample","id":"8d"},{"name":"sample","id":"50"}]}\n',
]

如果您按此处所示处理了回复:

var array = response.map(function(val) {
    return JSON.parse(val.trim())
})

然后核心功能应该起作用。

答案 1 :(得分:1)

运行代码段,您将看到与问题中提到的完全相同的输出。我希望这会对您(和其他人)有所帮助。编码愉快:)

<ul>
  {type
    .filter(item => {
      return item.name === companyType;
    })
    .map(item => {
      item.subcategory.map(subcategory => {
        <li key={subcategory}>
          <label id={subcategory} htmlFor={subcategory}>
            <input
              type="radio"
              name={subcategory}
              value={subcategory}
            />
            <span />
            {subcategory}
          </label>
        </li>;
      });
    })}
</ul>