如何检查一个JavaScript对象中的值是否存在于另一个JavaScript对象中? [英] How to check if values in one JavaScript object are present in another one?
问题描述
我试图比较json_str1和json_str2,这里它应该返回true,因为json_str1中的所有元素都存在于json_str2中。
I am trying to compare json_str1 and json_str2, here it should return true as all elements in json_str1 are present in json_str2.
现在我这样做很长像这样的方式
For now I am doing this the long way like this
json_str1 = '{"0":"a","1":"b","2":"c"}';
json_str2 = '{"0":"c","1":"b","2":"a"}';
json_obj1 = $.parseJSON(json_str1);
json_obj2 = $.parseJSON(json_str2);
arr1 = $.map(json_obj1, function(el) { return el });
arr2 = $.map(json_obj2, function(el) { return el });
if($(arr1).not(arr2).length === 0 && $(arr2).not(arr1).length === 0)
alert("equal");
else
alert("not equal");
如果不将对象转换为数组,我怎样才能简单明了?
How could I make it short and simple, without converting the objects into an array ?
https://jsfiddle.net/kq9gtdr0/
推荐答案
使用以下代码:
Object.keys(json_obj1) . every(k1 =>
Object.keys(json_obj2) . some(k2 =>
json_obj1[k1] === json_obj2[k2]
)
);
英文:
每个键
k1
在json_obj1
中满足某些条件键k2
injson_obj2
满足json_obj1的值
,键k1
等于json_obj2
的值,键k2
。
Every key
k1
injson_obj1
satisfies the condition that some keyk2
injson_obj2
satisifies the condition that the value ofjson_obj1
with keyk1
is equal to the value ofjson_obj2
with keyk2
.
或更多会话英语:
第一个对象中的每个值都匹配第二个中的某个值。
Every value in the first object matches some value in the second.
这篇关于如何检查一个JavaScript对象中的值是否存在于另一个JavaScript对象中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!