簡體   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