简体   繁体   中英

How to compare objects in a json array to another object

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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