[英]How do you compare keys & values in a JSON objects when one object has extra keys using Lodash?
I have two JSON objects like so:我有两个 JSON 对象,如下所示:
var obj1 = {a: "apple", b: "banana", c: "carrot"}
var obj2 = {a: "apple", e: “egg” b: "banana", c: "carrot", d: "dog"}
I want to be able to have a Boolean check comparing the two objects without having to remove data from either one.我希望能够对两个对象进行 Boolean 检查比较,而不必从任何一个对象中删除数据。 For example, if I were to use the data above, the Boolean check should return true because the values of the keys that are in both objects match.
例如,如果我要使用上面的数据,Boolean 检查应该返回true ,因为两个对象中的键值匹配。
However, lets say obj1
stays the same but obj2
is the following:但是,假设
obj1
保持不变,但obj2
如下:
var obj1 = {a: "apple", b: "banana", c: "carrot"}
var obj2 = {a: "ant", e: “egg” b: "banana", c: "carrot", d: "dog"}
With this data, it should return false because the a key's value is not matching even though other fields are matching and some fields are not present in both objects.对于此数据,它应该返回false ,因为即使其他字段匹配并且某些字段不存在于两个对象中,键的值也不匹配。
Any ideas?有任何想法吗? I would prefer to use Lodash since they have a quality library.
我更愿意使用 Lodash,因为他们有一个高质量的库。 Originally was trying to use
_.isEqual(obj1, obj2)
but it doesn't work for my exact needs.最初尝试使用
_.isEqual(obj1, obj2)
但它不能满足我的确切需求。
I don't know if lodash
has such a method.不知道
lodash
有没有这样的方法。 But you can achieve the same result by just utilizing Object.etnries
and Array.every
methods.但是您可以通过使用
Object.etnries
和Array.every
方法获得相同的结果。
var obj1 = { a: "apple", b: "banana", c: "carrot" } var obj2 = { a: "apple", b: "banana", c: "carrot", d: "dog", e: "egg" } var obj3 = {a: "apple", b: "banana", c: "carrot"} var obj4 = {a: "ant", e: "egg",b: "banana", c: "carrot", d: "dog"} function checkEquality(a, b) { const entries1 = Object.entries(a); const entries2 = Object.entries(b); const short = entries1.length > entries2? entries2: entries1; // pick the shorter array const long = short === entries1? b: a; const isEqual = short.every(([k, v]) => long[k] === v); return isEqual; } console.log(checkEquality(obj1, obj2)) console.log(checkEquality(obj3, obj4))
_.isMatch
can be of help. _.isMatch
可以提供帮助。 Check the below snippet检查下面的片段
var obj1 = { a: "apple", b: "banana", c: "carrot" } var obj2 = { a: "apple", e: "egg", b: "banana", c: "carrot", d: "dog" } console.log(_.isMatch(obj2, obj1)); var obj1 = { a: "apple", b: "banana", c: "carrot" } var obj2 = { a: "ant", e: "egg", b: "banana", c: "carrot", d: "dog" } console.log(_.isMatch(obj2, obj1));
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.20/lodash.min.js"></script>
Note that _.isMatch(obj1, obj2)
will not work.请注意
_.isMatch(obj1, obj2)
将不起作用。 You will need to put some logic to determine which object has more keys and pass it as first argument.您需要添加一些逻辑来确定哪个 object 具有更多键并将其作为第一个参数传递。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.