比较两个对象数组,只获取数组的不同属性

时间:2016-09-21 12:59:49

标签: javascript jquery arrays

Array1 = { "Name": "Max", "Occupation": "Agri", "Location": "KGP" }; 

Array2 = { "Name": "Alex", "Occupation": "S.E", "Location": "KGP" }; 

在上面给出的2个数组中,我在属性Name和Occupation中有不同的值,但该位置与Array1的值相同,

我想比较两个数组,只得到Array1的不同属性(Name和Occupation)

5 个答案:

答案 0 :(得分:1)

您可以迭代object1的键,并检查object2属性的差异。如果不相等,请将值分配给结果object3的属性。

var object1 = { "Name": "Max", "Occupation": "Agri", "Location": "KGP" },
    object2 = { "Name": "Alex", "Occupation": "S.E", "Location": "KGP" },
    object3 = {};

Object.keys(object1).forEach(function (k) {
    if (object1[k] !== object2[k]) {
        object3[k] = object1[k];
    }
});

console.log(object3);

答案 1 :(得分:1)

var obj1 = { "Name": "Max", "Occupation": "Agri", "Location": "KGP" }; 

var obj2 = { "Name": "Alex", "Occupation": "S.E", "Location": "KGP" }; 

function getDifference(obj1,obj2){
  var diff = [];
  Object.keys(obj1).forEach(function(key){
  if (obj1[key] !== obj2[key]) diff.push(key);
  });
  return diff;
}
console.log(getDifference(obj1,obj2));

答案 2 :(得分:0)

您的Array1和Array2是JavaScript Object。使用2个对象,您可以执行此工作,但脏对比。只要你有更多属性......这将是一团糟。

   var result = {};

    if (Array1.Name !== Array2.Name)
       result.Name = Array1.Name;
    if (Array1.Occupation !== Array2.Occupation)
       result.Occupation = Array1.Occupation.

   return result;

JavaScript中的数组使用以下语法声明:

var Array1 = [];

如果你想要一个对象数组,你可以写:

var Array1 = [ { "Name": "Max", "Occupation": "Agri", "Location": "KGP" }, { b"Name": "Max", "Occupation": "Agri", "Location": "KGP"} ]

但我怀疑这是你的意图。

答案 3 :(得分:0)

如果目标是获得不匹配的密钥,您可以尝试这样的事情:

function getMismatchKeys(o1,o2){
  return Object.keys(o1).filter(function(k){
    return o1.hasOwnProperty(k) && o2.hasOwnProperty(k) && o1[k] !== o2[k]
  });
}

var obj1 = { "Name": "Max", "Occupation": "Agri", "Location": "KGP" }; 
var obj2 = { "Name": "Alex", "Occupation": "S.E", "Location": "KGP" }; 

console.log(getMismatchKeys(obj1, obj2));

答案 4 :(得分:0)

我将假设Array1和Array2是json对象而不是json数组。我还假设您想要一个仅由Array1的键值对组成的结果对象,它与Array2不同。鉴于这些假设,您可以使用lodash omitBy来解决您的问题。

var Array1 = { "Name": "Max", "Occupation": "Agri", "Location": "KGP" };
var Array2 = { "Name": "Alex", "Occupation": "S.E", "Location": "KGP" };
var result = _.omitBy(Array1, function(val, key){ return val === Array2[key];});
console.log('the key value pairs of Array1 that are different from Array2 are: ', result);
<script src="https://cdn.jsdelivr.net/lodash/4.16.1/lodash.min.js"></script>