簡體   English   中英

按屬性將對象數組與另一個對象的鍵進行比較

[英]Compare array of objects by property with key of another object

我想將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" }
    ]
  }

因此,此代碼:

  1. 建立一個過濾器對象。 我們獲取wcObject.notCoveredList所有鍵,並使其成為單個對象(具有未定義值)的鍵,以便我們可以通過單個hasOwnProperty()調用來查找這些鍵,而無需在需要時遍歷數組過濾。
  2. data.examples數組的每個成員映射到其自己的name.desc屬性或[stripped name.value cover'] 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"]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM