如何使用Javascript(JS)比较两个单独数组中的两个对象值?

时间:2017-11-07 01:46:31

标签: javascript jquery underscore.js lodash

Lets说我有两个填充了对象的数组,这些数组具有多个属性,其中一些键是相同的。

        var array1 = [
          {name: "Jim", city: 'Toronto', id:'1281732'},
          {name: "Alex", city: 'New York', id:'32423'},
          {name: "Simon", city: 'San Francisco', id:'234234'},
          {name: "Jake", city: 'Milwaukee', id:'1282342341732'}
        ]

        var array2 = [
          {name: "Joey", city: 'Raleigh'},
          {name: "Alex", city: 'New York'},
          {name: "Lee", city: 'San Diego'},
          {name: "Jake", city: 'Milwaukee'}
        ]

如何通过比较名称和城市,找到array1中的第2个和第4个对象也可以在array2中找到。这意味着两个对象键必须匹配,然后从array1中获取重复的对象并推入一个新的数组。

使用lodash或undercores之类的东西是可以接受的。

2 个答案:

答案 0 :(得分:1)

与所有编程任务一样,您所做的就是思考问题并提出一个有意义的解决方案。在这种情况下,可以通过迭代第一个数组来搜索第二个数组中第一个数组中的每个项目,并在每次迭代时迭代第二个数组,直到找到匹配项。



var array1 = [
  {name: "Jim", city: 'Toronto', id:'1281732'},
  {name: "Alex", city: 'New York', id:'32423'},
  {name: "Simon", city: 'San Francisco', id:'234234'},
  {name: "Jake", city: 'Milwaukee', id:'1282342341732'}
]

var array2 = [
  {name: "Joey", city: 'Raleigh'},
  {name: "Alex", city: 'New York'},
  {name: "Lee", city: 'San Diego'},
  {name: "Jake", city: 'Milwaukee'}
]

var result = [];

for (var i = 0; i < array1.length; i++) {
  for (var j = 0; j < array2.length; j++) {
    if (array1[i].name == array2[j].name &&
        array1[i].city == array2[j].city) {
      result.push(array1[i]);
      break;
    }
  }
}

console.log(result);
&#13;
&#13;
&#13;

现代语法清理了一些。

&#13;
&#13;
var array1 = [
  {name: "Jim", city: 'Toronto', id:'1281732'},
  {name: "Alex", city: 'New York', id:'32423'},
  {name: "Simon", city: 'San Francisco', id:'234234'},
  {name: "Jake", city: 'Milwaukee', id:'1282342341732'}
]

var array2 = [
  {name: "Joey", city: 'Raleigh'},
  {name: "Alex", city: 'New York'},
  {name: "Lee", city: 'San Diego'},
  {name: "Jake", city: 'Milwaukee'}
]

var result = array1.filter(({name, city}) =>
  array2.some(o => o.name == name && o.city == city)
);

console.log(result);
&#13;
&#13;
&#13;

答案 1 :(得分:1)

为了获得两个数组中的结果,您还可以简单地使用filter()函数

 var array1 = [
          {name: "Jim", city: 'Toronto', id:'1281732'},
          {name: "Alex", city: 'New York', id:'32423'},
          {name: "Simon", city: 'San Francisco', id:'234234'},
          {name: "Jake", city: 'Milwaukee', id:'1282342341732'}
        ]

        var array2 = [
          {name: "Joey", city: 'Raleigh'},
          {name: "Alex", city: 'New York'},
          {name: "Lee", city: 'San Diego'},
          {name: "Jake", city: 'Milwaukee'}
        ]
        
 var array3 = array1.filter(row1 => array2.filter(row2 => row1.name == row2.name && row1.city == row2.city).length > 0);

console.log(array3);