按属性将对象数组与另一个对象的键进行比较

问题描述 投票:0回答:1

我想比较data.examples数组对象name.value属性值与wcObject.notCoveredList键,如果键匹配我想将wcObject的所有匹配值推送到数组以便在UI中显示。如果密钥不匹配,我希望通过删除末尾未覆盖的文本来推送data.examples数组对象的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" }
    ]
  }
javascript arrays angularjs foreach underscore.js
1个回答
0
投票

所以,这段代码:

  1. 构建过滤器对象。我们获取wcObject.notCoveredList的所有键,并将它们放在单个对象上(具有未定义的值),这样我们就可以通过单个hasOwnProperty()调用查找这些键,而不是在需要过滤时迭代数组。
  2. data.examples数组的每个成员映射到其自己的name.desc属性或[去除'未覆盖'] 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"]

© www.soinside.com 2019 - 2024. All rights reserved.