Home > Software engineering >  How does one compare every object-entry of an array-item to entries of another object while keeping/
How does one compare every object-entry of an array-item to entries of another object while keeping/

Time:01-06

I have an array of 2 objects [ { bg: 'a', o: 'c' }, {'hg': 'a2', 'oo': 'c3' } ] coming from a json file. And I want to compare each object in the array to another object that looks like this { fm: 'a', fh: 'b', o: 'a', fe: 'b', ft: 'a', fb: 'c', bg: 'f' } to determine if this object has both sets of key/value pairs in either of the objects in the json array. How can I compare these objects?

CodePudding user response:

The following approach utilizes

  • Object.entries in order to provide/access each of an object's key-value pair in its array/tuple form of [key, value].

  • Array.prototype.map in order to write for each array-item the boolean result of comparing every of its entries (key-value pairs) against an additionally provided object.

  • Array.prototype.every in order to retrieve the boolean value of comparing every of an array-item's entries (key-value pairs) against an additionally provided object.

const sampleArr = [ { bg: 'a', o: 'c' }, {'hg': 'a2', 'oo': 'c3' } ];
const sampleObj = { fm: 'a', fh: 'b', o: 'a', fe: 'b', ft: 'a', fb: 'c', bg: 'f' };


console.log("### How `Object.entries` works ###");
console.log({
  sampleArr
});
console.log(
  "sampleArr[0] => Object.entries(sampleArr[0]) ...",
  sampleArr[0], " => ",  Object.entries(sampleArr[0])
);
console.log(
  "sampleArr[1] => Object.entries(sampleArr[1]) ...",
  sampleArr[1], " => ",  Object.entries(sampleArr[1])
);


console.log("### Comparison 1 with what was provided by the OP ###");
console.log(
  sampleArr
    // create a new array which for each ...
    .map(item => {
      // ... `sampleArr` item retrieves/maps whether ...
      return Object
        .entries(item)
        // ... every entry of such an item exists
        // as entry of another provided object.
        .every(([key, value]) => sampleObj[key] === value)
    })
);


sampleArr.push({ o: 'a', ft: 'a', fh: 'b' }); // will match     ... maps to `true` value.
sampleArr.push({ o: 'a', ft: 'X', fh: 'b' }); // will not match ... maps to `false` value.

console.log("### Comparison 2 after pushing two more items into `sampleArr` ###");
console.log({
  sampleArr
});
console.log(
  sampleArr
    // create a new array which for each ...
    .map(item => {
      // ... `sampleArr` item retrieves/maps whether ...
      return Object
        .entries(item)
        // ... every entry of such an item exists
        // as entry of another provided object.
        .every(([key, value]) => sampleObj[key] === value)
    })
);
.as-console-wrapper { min-height: 100%!important; top: 0; }

  •  Tags:  
  • Related