如何根据多个唯一值过滤对象数组?

时间:2019-06-18 11:01:10

标签: javascript arrays filter

我有一个看起来像这样的数据集:

const data = [{
    "First Name" : "John"
    "Last Name": "Doe"
    "Cars Sold": 2
  },
  {
    "First Name" : "John"
    "Last Name": "Doe"
    "Cars Sold": 1
  },
  {
    "First Name" : "Jane"
    "Last Name": "Doe"
    "Cars Sold": 3
  }];

我将如何进行过滤以获取对象中所有人员的列表?即输出应该是对象中唯一身份人员的列表(姓和名的组合)。

谢谢

2 个答案:

答案 0 :(得分:4)

唯一的人,名字和姓氏用空格隔开:

const data = [{"First Name":"John", "Last Name":"Doe", "Cars Sold":2},{"First Name":"John", "Last Name":"Doe", "Cars Sold":1},{"First Name":"Jane", "Last Name":"Doe", "Cars Sold":3}];
const res = [...new Set(data.map(e => e["First Name"] + " " + e["Last Name"]))];
console.log(res);

ES5语法:

var data = [{"First Name":"John", "Last Name":"Doe", "Cars Sold":2},{"First Name":"John", "Last Name":"Doe", "Cars Sold":1},{"First Name":"Jane", "Last Name":"Doe", "Cars Sold":3}];
var res = data.map(function(e) {
  return e["First Name"] + " " + e["Last Name"];
}).filter(function(e, i, a) {
  return a.indexOf(e) == i;
});
console.log(res);

答案 1 :(得分:2)

const data = [{
    "First Name" : "John",
    "Last Name": "Doe",
    "Cars Sold": 2
  },
  {
    "First Name" : "John",
    "Last Name": "Doe",
    "Cars Sold": 1
  },
  {
    "First Name" : "Jane",
    "Last Name": "Doe",
    "Cars Sold": 3
  }];

const list = data.reduce((acc, cur) => acc.includes(`${cur['First Name']} ${cur['Last Name']}`) ? acc : acc.concat([`${cur['First Name']} ${cur['Last Name']}`]), []);

console.log(list);