如何检查一个JavaScript对象中的值是否存在于另一个JavaScript对象中? [英] How to check if values in one JavaScript object are present in another one?

查看:197
本文介绍了如何检查一个JavaScript对象中的值是否存在于另一个JavaScript对象中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图比较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 in json_obj2 满足 json_obj1的值,键 k1 等于 json_obj2 的值,键 k2

Every key k1 in json_obj1 satisfies the condition that some key k2 in json_obj2 satisifies the condition that the value of json_obj1 with key k1 is equal to the value of json_obj2 with key k2.

或更多会话英语:

第一个对象中的每个值都匹配第二个中的某个值。

Every value in the first object matches some value in the second.

这篇关于如何检查一个JavaScript对象中的值是否存在于另一个JavaScript对象中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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