通过属性与另一个对象的键比较对象数组

Compare array of objects by property with key of another object

本文关键字:比较 对象 数组 一个对象 属性      更新时间:2023-09-26

我想比较数据。示例数组对象名称。value property value with wcObject。notCoveredList键,如果键匹配,我想推所有匹配值的wcObject到一个数组,以便在UI中显示。如果键不匹配,我想要data的name.desc属性值。通过推入的数组对象的例子,删除末尾未覆盖的文本。

    data = {
        examples : [
          {
            name: {
              value:"someOne",
              desc: "some random word not covered"
            },
            type: {
              value:"General",
              desc:"General"
            }
          }, {
            name: {
              value:"secondOne",
              desc: "second on in the queue not covered"
            },
            type: {
              value:"General",
              desc:"General"
            }
          }, {
            name: {
              value:"thirdOne",
              desc: "third one from the last not covered"
            },
            type: {
              value:"General",
              desc:"General"
            }
          }
        ]
      }
 wcObject = {
    notCoveredList : [
      { someOne: "anyone can start " },
      { secondOne: "second One cannot start" },
      { thirdOne: "third One can be allowed" }
    ]
  }

那么,下面的代码:

  1. 建立一个过滤器对象。我们获取所有的键wcObject.notCoveredList,并使它们成为单个对象上的键一个未定义的值),这样我们就可以用单个键来查找这些键当我们需要过滤时,调用hasOwnProperty()而不是在数组上迭代。
  2. data.examples数组的每个成员映射到它自己的name.desc属性或[去掉' not covered'] name.value属性。

.

wcNotCoveredKeys = wcObject.notCoveredList.reduce((memo, item) => {
  // value is empty for all, we only care about keys.
  memo[Object.keys(item)[0]] = undefined;
  return memo;
}, {})
// having built up our lookup table of those not covered, we continue:
forUI = data.examples.map(example => {
  if (wcNotCoveredKeys.hasOwnProperty(example.name.value)) {
    return example.name.value;
  }
  else {
    notCoveredString = example.name.desc;
    cutOutIndex = notCoveredString.indexOf(' not covered');
    return notCoveredString.slice(0, cutOutIndex)
  }
});

(更新为集成字符串切片)

只是要清楚:如果您从wcObject中删除了第二个项目。notCoveredList,那么您将在forUI中得到的输出(给定您提供的示例数据结构/值)将是

["someOne", "second on in the queue", "thirdOne"]