比较两个对象数组,并使用loadash返回一个具有公共值的数组

时间:2018-12-30 15:11:55

标签: javascript arrays

我必须排列对象数组,让其看起来像这样:

var result1 = [
{id:1, name:'Sandra', type:'user', username:'sandra'},
{id:2, name:'John', type:'admin', username:'johnny2'},
{id:3, name:'Peter', type:'user', username:'pete'},
{id:4, name:'Bobby', type:'user', username:'be_bob'}
]; 

var result2 = [
{id:2, name:'John', type:'admin', username:'johnny2'},
{id:3, name:'Peter', type:'user', username:'pete'},
];

如何使用loadash获取两个数组中都存在的对象? 还有,如果我们有N个对象数组,并且想要将它们全部比较并在数组中获得公共值,该怎么办?

2 个答案:

答案 0 :(得分:1)

您只需使用filtersome

var result1 = [
  {id:1, name:'Sandra', type:'user', username:'sandra'},
  {id:2, name:'John', type:'admin', username:'johnny2'},
  {id:3, name:'Peter', type:'user', username:'pete'},
  {id:4, name:'Bobby', type:'user', username:'be_bob'}
]; 

var result2 = [
  {id:2, name:'John', type:'admin', username:'johnny2'},
  {id:3, name:'Peter', type:'user', username:'pete'},
  {id:15, name:'Pe', type:'usefghjr', username:'pete'},
];

let op = result2.filter(e => result1.some(el => el.id === e.id))

console.log(op);

如果我有更多阵列怎么办

var result1 = [
  {id:1, name:'Sandra', type:'user', username:'sandra'},
  {id:2, name:'John', type:'admin', username:'johnny2'},
  {id:3, name:'Peter', type:'user', username:'pete'},
  {id:4, name:'Bobby', type:'user', username:'be_bob'}
]; 

var result2 = [
  {id:2, name:'John', type:'admin', username:'johnny2'},
  {id:3, name:'Peter', type:'user', username:'pete'},
  {id:15, name:'Pe', type:'usefghjr', username:'pete'},
];

var result3 = [{id:3, name:'Peter', type:'user', username:'pete'}];

let array = [result1,result2,result3]

let op = result2.filter(ele => array.every(el => el.some(val => val.id === ele.id)))

console.log(op);

答案 1 :(得分:0)

您可以使用所有id构建一个Set,并通过检查具有相同id的公共对象来过滤数组。

var result1 = [{ id: 1, name: 'Sandra', type: 'user', username: 'sandra' }, { id: 2, name: 'John', type: 'admin', username: 'johnny2' }, { id: 3, name: 'Peter', type: 'user', username: 'pete' }, { id: 4, name: 'Bobby', type: 'user', username: 'be_bob' }],
    result2 = [{ id: 2, name: 'John', type: 'admin', username: 'johnny2' }, { id: 3, name: 'Peter', type: 'user', username: 'pete' }],
    common = [result1, result2].reduce((a, b) => {
        var s = new Set(a.map(({ id }) => id));
        return b.filter(({ id }) => s.has(id));            
    });

console.log(common);