数组中对象的值唯一在一起

时间:2018-03-15 16:34:47

标签: javascript typescript

我有一个对象数组

[
  {"first_name" :"John", "last_name": "Smith",  "course": "course 1"}, 
  {"first_name" :"Joe", "last_name": "Doe",  "course": "course 2"}, 
  {"first_name" :"John", "last_name": "Smith",  "course": "course 3"} 
] 

如何抓住唯一的first_namelast_name来获取:

[
  {"first_name" :"John", "last_name": "Smith",  "course": "course 1"}, 
  {"first_name" :"Joe", "last_name": "Doe",  "course": "course 2"}
] 

在新数组中?

3 个答案:

答案 0 :(得分:1)

您可以尝试使用Array.filter



var arr = [
  {"first_name" :"John", "last_name": "Smith",  "course": "course 1"}, 
  {"first_name" :"Joe", "last_name": "Doe",  "course": "course 2"}, 
  {"first_name" :"John", "last_name": "Smith",  "course": "course 3"} 
]; 

var map = {}; // create a map that stores unique combination of fields (first_name and last_name)

arr = arr.filter(function(item){
  if(!map[item.first_name + "_" + item.last_name]) { 
    // store the first occurrence of combination in map and ignore others
    map[item.first_name + "_" + item.last_name] = "first_unique_record";
    return true;
  }
  return false;
});

console.log(arr);




答案 1 :(得分:0)

在函数 .filter(collection,[predicate = .identity])或 .find(collection,[predicate = .identity)中使用lodash Lodash ],[fromIndex = 0])

答案 2 :(得分:0)

我不确定这是否是最好的代码,但我以这种方式解决了我的问题:

var dataJson = [
    {"first_name" :"John", "last_name": "Smith",  "course": "course 1"}, 
    {"first_name" :"Joe", "last_name": "Doe",  "course": "course 2"}, 
    {"first_name" :"John", "last_name": "Smith",  "course": "course 3"} 
   ];

   var tmparr = [];

   var newJson = [];
   var duplicatesJson = [];

   dataJson.forEach((value, index) => {
                let a = value.first_name + value.last_name
                        if(!(this.tmparr.includes(a))){
                        console.log('unique');             
                        this.tmparr.push(a);
                        this.newJson.push(value);
                        } else {
                        console.log('duplicate')
                        this.duplicatesJson.push(value);                            
                        }
            })

   console.log(this.newJson);
   console.log(this.duplicatesJson)