如何将数组项的每个对象条目与另一个对象的条目进行比较,同时保留/记住每个比较结果



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

以下方法利用

  • Object.entries,以便以[key, value]的数组/元组形式提供/访问对象的每个键值对。

  • Array.prototype.map,以便为每个数组项写入将其每个条目(键值对(与额外提供的对象进行比较的布尔结果。

  • Array.prototype.every,以便检索将数组项的每个条目(键值对(与额外提供的对象进行比较的布尔值。

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

相关内容

  • 没有找到相关文章

最新更新