NodeJS 在javascript中获取不同的对象数组

guicsvcw  于 2023-01-30  发布在  Node.js
关注(0)|答案(3)|浏览(185)

对象的不同数组,如下所示;我想得到唯一的对象数组。
阵列示例:

const data = [ { "name": "abc", age: "31", project: "Java" }, { "name": "abc", age: "31", project: "Java" }, { "name": "abc", age: "29", project: "Javascript" }, { "name": "abc", age: "31", project: "C++" }, { "name": "abc", age: "31", project: "Java" }, { "name": "abc", age: "31", project: "Java" }]

预期输出:

const data = [ { "name": "abc", age: "31", project: "Java" },{ "name": "abc", age: "29", project: "Javascript" }, { "name": "abc", age: "31", project: "C++" }]
5gfr0r5j

5gfr0r5j1#

let unique = [...new Set(data.map(i => JSON.stringify(i)))].map(i => JSON.parse(i));
0wi1tuuw

0wi1tuuw2#

这种方法强制执行一致的键顺序,并在每个对象上使用JSON.stringify来测试唯一性。

const data = [ { "name": "abc", age: "31", project: "Java" }, { "name": "abc", age: "31", project: "Java" }, { "name": "abc", age: "29", project: "Javascript" }, { "name": "abc", age: "31", project: "C++" }, { "name": "abc", age: "31", project: "Java" }, { "name": "abc", age: "31", project: "Java" }]

const result = [...new Set(data.map(i=>JSON.stringify(Object.fromEntries(
  Object.entries(i).sort(([a],[b])=>a.localeCompare(b))))
))].map(JSON.parse)

console.log(result)
pdkcd3nj

pdkcd3nj3#

根据您的数据,project属性包含动态值。因此,您可以使用Array.filter()方法在单行代码中过滤出重复的值。
现场演示**:**

const data = [ { "name": "abc", age: "31", project: "Java" }, { "name": "abc", age: "31", project: "Java" }, { "name": "abc", age: "29", project: "Javascript" }, { "name": "abc", age: "31", project: "C++" }, { "name": "abc", age: "31", project: "Java" }, { "name": "abc", age: "31", project: "Java" }];

const uniq = {};

var arrFiltered = data.filter(obj => !uniq[obj.project] && (uniq[obj.project] = true));

console.log(arrFiltered);

相关问题