查找数组对象的值差异

时间:2017-11-08 03:35:15

标签: javascript lodash

我有两个数组,它们都包含随机键和值。我有一个更新的对象和当前对象。但更新的对象包含新值和旧值。我想找到这两个对象键和值之间的差异,以使用新的键或值生成新的更新对象。

当前对象

{
  key1: "abc"
  key2: "ggg"
  key3: 0,
  key4: ["1","3","5"]
  key5: [1,2,3,4,5]
  key6: [9,8,7,6],
  key7: false
}

更新对象

{
  key1: "abc"
  key2: "new"
  key3: 30,
  key4: ["1","3","5"]
  key5: [2,3,4]
  key6: [],
  key7: true,
  special8: [1,2,3]
}

结果

{
  key2: "new"
  key3: 30,
  key5: [2,3,4]
  key6: [],
  key7: true,
  special8: [1,2,3]
}

3 个答案:

答案 0 :(得分:2)

根据您的条件:以下reduce()函数将每个updated对象的属性与每个current对象的属性进行比较,并返回包含差异的全新对象。

请注意:使用key4简单地比较字符串数组(例如!==属性)可以返回错误否定,因此使用JSON.stringify()

// Current Object.
const current = {
  key1: "abc",
  key2: "ggg",
  key3: 0,
  key4: ["1","3","5"],
  key5: [1,2,3,4,5],
  key6: [9,8,7,6],
  key7: false
}

// Updated Object.
const updated = {
  key1: "abc",
  key2: "new",
  key3: 30,
  key4: ["1","3","5"],
  key5: [2,3,4],
  key6: [],
  key7: true,
  special8: [1,2,3]
}

// Difference Object.
const difference = (Object.keys(updated)).reduce((difference, key) => {

  // Same?
  if (JSON.stringify(updated[key]) == JSON.stringify(current[key])) return difference 

  // Different.
  return {...difference, [key]: updated[key]}

}, {})

console.log(difference)

答案 1 :(得分:0)

以下内容将解决您的需求:

<article>
  <section>content</section>
  <section>content</section>
  <section>cell3</section>
  <section>cell4</section>
</article>

答案 2 :(得分:0)

这是另一种解决方案:

我们将使用两种不同的功能。等于函数的目的是查看相等的特定对象是否等于:

function equals(obj1, obj2) {
    let equals = true;
    if (!obj1) return;
    if (obj1.length == obj2.length) {
        for (var index in obj1) {
            if (obj1[index] != obj2[index]) {
                return false;
            }
        }
    } else return false;
    return true;
}

然后,实际的printDifferences函数利用上述函数来检查两个对象的差异。然后以另一个对象的形式返回。

function printDifferences(object1, object2) {
    let newObj = {};
    for (var key in object2) {
        if ((typeof object1[key] == "object" && !equals(object1[key], object2[key])) ||
            (typeof object1[key] != "object" && object1[key] != object2[key]) ||
            object1[key] == undefined) {
            newObj[key] = object2[key];
        }
    }
    return newObj;
}

console.log(printDifferences(current, updated))