如何使用节点js从json数组中删除重复值?

时间:2017-11-07 04:03:03

标签: arrays json node.js

我的json数组输入如下: -

var temp =  [{first: 569, second: "789", third: "458"},  {first: value1, 476: "147", third: "369"},  {first: 100, second: "200", third: "300"},  {first: 100, second: "200", third: "300"},   {first: 100, second: "200", third: "300"}];

我想从中删除重复项,需要输出如下:

var temp =  [{first: 569, second: "789", third: "458"},  {first: value1, 476: "147", third: "369"},  {first: 100, second: "200", third: "300"}];

我怎样才能实现这个目标?

1 个答案:

答案 0 :(得分:1)

您可以使用array#mapJSON.stringify从对象创建字符串,然后使用Set获取所有唯一字符串,然后使用array#map和{{转换回对象1}}。

如果数据类型不是JSON,则以下提案将无效。

JSON.parse()
const temp =  [{first: 569, second: "789", third: "458"},  {first: 476, second : "147", third: "369"},  {first: 100, second: "200", third: "300"},  {first: 100, second: "200", third: "300"},   {first: 100, second: "200", third: "300"}];

const result = [...new Set(temp.map(obj => JSON.stringify(obj)))]
                 .map(str => JSON.parse(str));
console.log(result);