如何检查一个JavaScript对象中的值是否存在于另一个JavaScript对象中?

时间:2021-04-19 21:21:31

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.

我试图比较json_str1和json_str2,这里它应该返回true,因为json_str1中的所有元素都存在于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/

https://jsfiddle.net/kq9gtdr0/

7 个解决方案

#1


13  

Use the following code:

使用以下代码:

Object.keys(json_obj1) . every(k1 => 
  Object.keys(json_obj2) . some(k2 =>
    json_obj1[k1] === json_obj2[k2]
  )
);

In English:

用英语:

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.

json_obj1中的每个密钥k1满足json_obj2中的某个密钥k2满足条件,即具有密钥k1的json_obj1的值等于具有密钥k2的json_obj2的值。

Or in more conversational English:

或者更多会话英语:

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

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

#2


2  

Using lodash

使用lodash

var _ = require('lodash');

function compareValues(jstr1, jstr2) {
  return _.isEqual(_.valuesIn(JSON.parse(jstr1)).sort(), _.valuesIn(JSON.parse(jstr2)).sort());
}

json_str1 = '{"0":"a","1":"b","2":"c"}';
json_str2 = '{"0":"c","1":"b","2":"a"}';

console.log(compareValues(json_str1, json_str2));

#3


1  

There is short and easy accurate way to this.

有一个简短而准确的方法。

You can use a third party but extremely popular utility library called Lodash. Chaining functions you can check for equality.

您可以使用第三方但非常受欢迎的实用程序库Lodash。链接功能可以检查是否相等。

  1. First parse both JSON into objects
  2. 首先将JSON解析为对象
  3. Then use _.values() to extract the values of all keys of each into separate arrays
  4. 然后使用_.values()将每个键的值提取到单独的数组中
  5. Find difference of two arrays. If its an empty array then both of them are equal.
  6. 找出两个数组的差异。如果它是一个空数组,那么它们都是相等的。

You can chain all the steps into one statement like:

您可以将所有步骤链接到一个语句中,如:

_.isEmpty(_.difference(_.values(json_obj1), _.values(json_obj2)))

Example: https://jsfiddle.net/kq9gtdr0/4/

示例:https://jsfiddle.net/kq9gtdr0/4/

For more information:

了解更多信息:

https://lodash.com/docs#values

https://lodash.com/docs#values

https://lodash.com/docs#difference

https://lodash.com/docs#difference

https://lodash.com/docs#isEmpty

https://lodash.com/docs#isEmpty

You can include the library from CDN(https://cdn.jsdelivr.net/lodash/4.5.1/lodash.min.js) or download and use it as normal script. Lodash offers plenty of useful utility functions that makes JS programming a lot easier. You better try it out.

您可以从CDN(https://cdn.jsdelivr.net/lodash/4.5.1/lodash.min.js)中包含该库,或者下载并将其用作普通脚本。 Lodash提供了大量有用的实用功能,使JS编程变得更加容易。你最好试一试。

#4


1  

If you prefer using libraries, then you could use underscore isMatch

如果您更喜欢使用库,那么您可以使用下划线isMatch

_.isMatch(object, properties)

Tells you if the keys and values in properties are contained in object.

告诉您属性中的键和值是否包含在对象中。

#5


-1  

You can try this

你可以试试这个

var json_str1 = {"0":"a","1":"b","2":"c"};
var json_str2 = {"0":"c","1":"b","2":"a"};
var flag =  1;

if(Object.keys(json_str1).length == Object.keys(json_str2).length){
    Object.keys(json_str1).forEach(function(x){
        if(!json_str2.hasOwnProperty(x) || json_str2[x] != json_str1[x]){
            flag = 0;
            return;
        }                      
    });
}

if(flag)
    alert('equal');
else
    alert('Not Equal');

#6


-1  

If you want to find out if both Objects have the same keys there is no way to do this without at least converting the keys of both Objects to an array with Object.keys or looping through both Objects!

如果你想知道两个对象是否都有相同的密钥,那么如果没有至少将两个对象的密钥转换为带有Object.keys的数组或循环遍历这两个对象,则无法做到这一点!

The reason is simple: It's clear that you have to compare the number of keys of both Objects and the only way to do this is by looping through all properties or Object.keys.

原因很简单:很明显,您必须比较两个对象的键数,唯一的方法是循环遍历所有属性或Object.keys。

So I think the shortest way to do this is:

所以我认为最简单的方法是:

json_obj1 = JSON.parse('{"0":"a","1":"b","2":"c"}');
json_obj2 = JSON.parse('{"0":"c","1":"b","2":"a"}');

keys_1 = Object.keys(json_obj1);
keys_2 = Object.keys(json_obj2);

if(keys_1.length === keys_2.length && keys_1.every(key => keys_2.indexOf(key) >= 0)) {
    alert('equal')
} else {
    alert('not equal')
}

If you only want to check if all keys from json1 are present in json2 you can do:

如果您只想检查json1中是否存在json1中的所有键,您可以执行以下操作:

json_obj1 = JSON.parse('{"0":"a","1":"b","2":"c"}');
json_obj2 = JSON.parse('{"0":"c","1":"b","2":"a"}');
if(Object.keys(json_obj1).every(key => key in json_obj2)) {
  alert('equal');
} else {
  alert('not equal');
}

#7


-1  

In your question and comments you indicate you are only looking to verify that "all elements in json_str1 are present in json_str2". Your example code doesn't just do that, it checks for the complete equality of keys by testing if all the keys (not values) in the first object are in the second object AND all the keys in the second object are in the first object. By looking at your code, i assume that when you say "elements" you mean keys.

在您的问题和评论中,您表明您只想验证“json_str1中的所有元素都存在于json_str2中”。您的示例代码不只是这样做,它通过测试第一个对象中的所有键(而不是值)是否在第二个对象中并且第二个对象中的所有键都在第一个对象中来检查键的完全相等性。通过查看您的代码,我假设当您说“元素”时,您的意思是键。

All that aside, this might help:

除此之外,这可能会有所帮助:

// Your first few lines of code

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);

// My new code

var values1 = Object.keys(json_obj1).map(key => json_obj1[key]);
var values2 = Object.keys(json_obj2).map(key => json_obj2[key]);

// Check if every key in the first object is in the second object.
values1.every(k1 => values2.indexOf(k1) >= 0);

// OR

// Check for equality of keys by checking both directions.
values1.every(k1 => values2.indexOf(k1) >= 0) && values2.every(k2 => values1.indexOf(k2) >= 0);

That's 2 lines to get the keys, and one line to check. You only need one of those two checks.

这是获得密钥的两行,还有一行要检查。您只需要这两项检查中的一项。

#1


13  

Use the following code:

使用以下代码:

Object.keys(json_obj1) . every(k1 => 
  Object.keys(json_obj2) . some(k2 =>
    json_obj1[k1] === json_obj2[k2]
  )
);

In English:

用英语:

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.

json_obj1中的每个密钥k1满足json_obj2中的某个密钥k2满足条件,即具有密钥k1的json_obj1的值等于具有密钥k2的json_obj2的值。

Or in more conversational English:

或者更多会话英语:

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

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

#2


2  

Using lodash

使用lodash

var _ = require('lodash');

function compareValues(jstr1, jstr2) {
  return _.isEqual(_.valuesIn(JSON.parse(jstr1)).sort(), _.valuesIn(JSON.parse(jstr2)).sort());
}

json_str1 = '{"0":"a","1":"b","2":"c"}';
json_str2 = '{"0":"c","1":"b","2":"a"}';

console.log(compareValues(json_str1, json_str2));

#3


1  

There is short and easy accurate way to this.

有一个简短而准确的方法。

You can use a third party but extremely popular utility library called Lodash. Chaining functions you can check for equality.

您可以使用第三方但非常受欢迎的实用程序库Lodash。链接功能可以检查是否相等。

  1. First parse both JSON into objects
  2. 首先将JSON解析为对象
  3. Then use _.values() to extract the values of all keys of each into separate arrays
  4. 然后使用_.values()将每个键的值提取到单独的数组中
  5. Find difference of two arrays. If its an empty array then both of them are equal.
  6. 找出两个数组的差异。如果它是一个空数组,那么它们都是相等的。

You can chain all the steps into one statement like:

您可以将所有步骤链接到一个语句中,如:

_.isEmpty(_.difference(_.values(json_obj1), _.values(json_obj2)))

Example: https://jsfiddle.net/kq9gtdr0/4/

示例:https://jsfiddle.net/kq9gtdr0/4/

For more information:

了解更多信息:

https://lodash.com/docs#values

https://lodash.com/docs#values

https://lodash.com/docs#difference

https://lodash.com/docs#difference

https://lodash.com/docs#isEmpty

https://lodash.com/docs#isEmpty

You can include the library from CDN(https://cdn.jsdelivr.net/lodash/4.5.1/lodash.min.js) or download and use it as normal script. Lodash offers plenty of useful utility functions that makes JS programming a lot easier. You better try it out.

您可以从CDN(https://cdn.jsdelivr.net/lodash/4.5.1/lodash.min.js)中包含该库,或者下载并将其用作普通脚本。 Lodash提供了大量有用的实用功能,使JS编程变得更加容易。你最好试一试。

#4


1  

If you prefer using libraries, then you could use underscore isMatch

如果您更喜欢使用库,那么您可以使用下划线isMatch

_.isMatch(object, properties)

Tells you if the keys and values in properties are contained in object.

告诉您属性中的键和值是否包含在对象中。

#5


-1  

You can try this

你可以试试这个

var json_str1 = {"0":"a","1":"b","2":"c"};
var json_str2 = {"0":"c","1":"b","2":"a"};
var flag =  1;

if(Object.keys(json_str1).length == Object.keys(json_str2).length){
    Object.keys(json_str1).forEach(function(x){
        if(!json_str2.hasOwnProperty(x) || json_str2[x] != json_str1[x]){
            flag = 0;
            return;
        }                      
    });
}

if(flag)
    alert('equal');
else
    alert('Not Equal');

#6


-1  

If you want to find out if both Objects have the same keys there is no way to do this without at least converting the keys of both Objects to an array with Object.keys or looping through both Objects!

如果你想知道两个对象是否都有相同的密钥,那么如果没有至少将两个对象的密钥转换为带有Object.keys的数组或循环遍历这两个对象,则无法做到这一点!

The reason is simple: It's clear that you have to compare the number of keys of both Objects and the only way to do this is by looping through all properties or Object.keys.

原因很简单:很明显,您必须比较两个对象的键数,唯一的方法是循环遍历所有属性或Object.keys。

So I think the shortest way to do this is:

所以我认为最简单的方法是:

json_obj1 = JSON.parse('{"0":"a","1":"b","2":"c"}');
json_obj2 = JSON.parse('{"0":"c","1":"b","2":"a"}');

keys_1 = Object.keys(json_obj1);
keys_2 = Object.keys(json_obj2);

if(keys_1.length === keys_2.length && keys_1.every(key => keys_2.indexOf(key) >= 0)) {
    alert('equal')
} else {
    alert('not equal')
}

If you only want to check if all keys from json1 are present in json2 you can do:

如果您只想检查json1中是否存在json1中的所有键,您可以执行以下操作:

json_obj1 = JSON.parse('{"0":"a","1":"b","2":"c"}');
json_obj2 = JSON.parse('{"0":"c","1":"b","2":"a"}');
if(Object.keys(json_obj1).every(key => key in json_obj2)) {
  alert('equal');
} else {
  alert('not equal');
}

#7


-1  

In your question and comments you indicate you are only looking to verify that "all elements in json_str1 are present in json_str2". Your example code doesn't just do that, it checks for the complete equality of keys by testing if all the keys (not values) in the first object are in the second object AND all the keys in the second object are in the first object. By looking at your code, i assume that when you say "elements" you mean keys.

在您的问题和评论中,您表明您只想验证“json_str1中的所有元素都存在于json_str2中”。您的示例代码不只是这样做,它通过测试第一个对象中的所有键(而不是值)是否在第二个对象中并且第二个对象中的所有键都在第一个对象中来检查键的完全相等性。通过查看您的代码,我假设当您说“元素”时,您的意思是键。

All that aside, this might help:

除此之外,这可能会有所帮助:

// Your first few lines of code

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);

// My new code

var values1 = Object.keys(json_obj1).map(key => json_obj1[key]);
var values2 = Object.keys(json_obj2).map(key => json_obj2[key]);

// Check if every key in the first object is in the second object.
values1.every(k1 => values2.indexOf(k1) >= 0);

// OR

// Check for equality of keys by checking both directions.
values1.every(k1 => values2.indexOf(k1) >= 0) && values2.every(k2 => values1.indexOf(k2) >= 0);

That's 2 lines to get the keys, and one line to check. You only need one of those two checks.

这是获得密钥的两行,还有一行要检查。您只需要这两项检查中的一项。