【问题标题】:How does one compare every object-entry of an array-item to entries of another object while keeping/remembering each comparison result?如何在保持/记住每个比较结果的同时将数组项的每个对象条目与另一个对象的条目进行比较?
【发布时间】:2023-04-07 02:13:01
【问题描述】:

我有一个来自 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 数组中的任一对象中都具有两组键/值对。如何比较这些对象?

【问题讨论】:

  • 您希望单个对象成为数组中两个对象并集的超集吗?或者您想查看数组中的任何一个对象是否是单个对象的子集?您能否添加一些示例数据,包括每种情况下的预期结果?
  • 我想看看数组中的任何一个对象是否是单个对象的子集。在第一个 json 对象中,我希望它匹配资产名称中的键/值对。经过一点操作后,它被放入这样的对象中。 {fm: 'a', fh: 'b', o: 'c', fe: 'b', ft: 'a', fb: 'c', bg: 'a' } 我希望第二个对象不观看任何资产。
  • 没有什么比得上 JSON 数组或 JSON 对象了。 JS 数据结构可以作为JSON 字符串提供和传输/交换(参见JSON.stringify)。这样的字符串可以通过像JSON.parse 这样的解析过程转换回对象。因此JSON 代表两者,一个带有方法的 JavaScript 命名空间和一个用于序列化数据结构的语法。

标签: javascript arrays data-structures comparison key-value


【解决方案1】:

以下方法利用

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

【讨论】:

  • 谢谢,这非常有帮助。
猜你喜欢
  • 1970-01-01
  • 2018-08-04
  • 1970-01-01
  • 2021-09-09
  • 1970-01-01
  • 1970-01-01
  • 2015-05-23
  • 2014-09-21
  • 1970-01-01
相关资源
最近更新 更多