获取JavaScript中两个对象之间的区别的属性 [英] Get the property of the difference between two objects in javascript

查看:70
本文介绍了获取JavaScript中两个对象之间的区别的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们说我有一个看起来像这样的对象:

Let's say that I have an object which looks like this:

{
  prop1: false,
  prop2: false,
  prop3: false
}

和另一个对象看起来像这样:

and another object which looks like this:

{
  prop1: false,
  prop2: true,
  prop3: false
}

其中差异在 prop2之内属性。是否有任何方法或库(虽然首选香草)可以比较两个对象,找到具有不同值的属性,然后返回属性名称(在本例中为 prop2 ) ?

where the difference is within the prop2 property. Is there any way or library (vanilla preferred though) which will compare the two objects, find the property with the different value, and return the property name (in this case prop2)?

我尝试在lodash中使用Difference和DifferenceBy函数没有成功。

I have tried using the difference and differenceBy functions in lodash to no success. Any help or suggestions will be greatly appreciated!

推荐答案

您可以通过检查不相等的值来过滤键(假定键相同)。

You could filter the keys (assuming same keys) by checking the unequal value.

var obj1 = { prop1: false, prop2: false, prop3: false },
    obj2 = { prop1: false, prop2: true, prop3: false },
    difference = Object.keys(obj1).filter(k => obj1[k] !== obj2[k]);
    
console.log(difference);

这篇关于获取JavaScript中两个对象之间的区别的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆