简体   繁体   English

如何基于javascript中的键名比较两个JSON值?

[英]How to compare two JSON values based on the key name in javascript?

I have two JSON arrays like 我有两个像JSON数组

array1=[{a:1,b:2,c:3,d:4}]
&
array2=[{a:2,b:5,c:3,d:4}]

Is there any method to find the value of one of the keys in array1 present in array 2.Here in the array 1 key b contains the value 2,and array2 also contain a key a with value 2. How can I capture the key name of array 2 which has the same value for one of the keys in array. 有什么方法可以找到数组2中存在的array1中的键之一的值。在数组1中,键b包含值2,而array2也包含具有值2的键a。如何捕获键名数组2的值与数组中的键之一具有相同的值。

I don't quite understand if you are interested in operating on arrays or objects - as your example is a pair of single element arrays, and the comparison is clearly between the objects in the arrays. 我不太了解您是否有兴趣对数组或对象进行操作-因为您的示例是一对单元素数组,所以比较显然是在数组中的对象之间进行比较。

That said, if your goal is to compare two objects, and return the set of keys that are the same for both, you would do something like 也就是说,如果您的目标是比较两个对象,并返回两个相同的键集,则可以执行以下操作

obj1 = {a:1,b:2,c:3,d:4};
obj2 = {a:2,b:5,c:3,d:4};

function sameKeys(a,b) {
    return Object.keys(a).filter(function(key) {
        return a[key] === b[key];
    });
}

console.log(sameKeys(obj1, obj2));

When I run this, I get: 运行此命令时,我得到:

[ 'c', 'd' ]

I hope that is what you were asking... 我希望这就是你要的...

Wrote a prototype function to compare an object against another. 编写了原型函数,将一个对象与另一个对象进行比较。

var obj1 = {a: 1, b: 2, c: 3, d: 4};
var obj2 = {a: 2, b: 4, c: 100, d: 200}


Object.prototype.propertiesOf = function(visitorObj) {

   result = {};

   //Go through the host object 
   for (thisKey in this) {

        //Exclude this function
        if (!this.hasOwnProperty(thisKey))
          continue;

        //Compare the visitor object against the current property
        for (visitorKey in visitorObj) {
           if (visitorObj[visitorKey] === this[thisKey])
              result[visitorKey] = thisKey;               
      }   
   } 

  return result;

}

console.log(obj1.propertiesOf(obj2));

Simply call the propertiesOf function of any object by passing another object as the argument. 只需通过传递另一个对象作为参数来调用任何对象的propertiesOf函数。 It returns an object which has similar keys linked to each other. 它返回一个对象,该对象具有彼此链接的相似键。

The above example will result in: 上面的示例将导致:

{a: "b", b: "d"}

It seems you want something like this: make a function that finds all the keys in the 2nd object that have a given value. 看来您想要这样的事情:创建一个函数,以查找第二个对象中具有给定值的所有键。 Then pass the value from the first object to that function. 然后将值从第一个对象传递到该函数。

obj1={a:1,b:2,c:3,d:4};
obj2={a:2,b:5,c:3,d:4};
function findKeysByValue(obj, v) {
    var results = [];
    for (var k in obj) {
        if (obj.hasOwnProperty(k) && v == obj[k]) {
            results.push(k);
        }
    }
    return results;
}
console.log(findKeysByValue(obj2, obj1['b']));   // ['a']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM