Nikhil Bharadwaj
Nikhil Bharadwaj

Reputation: 917

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

I have two JSON arrays like

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.

Upvotes: 2

Views: 7731

Answers (3)

Stuart
Stuart

Reputation: 9858

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']

Upvotes: 0

Charlie
Charlie

Reputation: 23798

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. It returns an object which has similar keys linked to each other.

The above example will result in:

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

Upvotes: 0

N. Leavy
N. Leavy

Reputation: 1094

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...

Upvotes: 1

Related Questions