繁体   English   中英

如何将 json 数组中的对象与另一个 object 进行比较

[英]How to compare objects in a json array to another object

我有一个来自 json 文件的 2 个对象数组[ { bg: 'a', o: 'c' }, {'hg': 'a2', 'oo': 'c3' } ] 我想将数组中的每个 object 与另一个看起来像这样的 object 进行比较{ fm: 'a', fh: 'b', o: 'a', fe: 'b', ft: 'a', fb: 'c', bg: 'f' }确定此 object 是否在 json 数组中的任一对象中都有两组键/值对。 如何比较这些对象?

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

暂无
暂无

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

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