簡體   English   中英

如何在有條件的情況下加入兩個不同的 arrays?

[英]How can I join two different arrays with condition?

我有兩個 arrays 數據如下

const arr1 = [{ agentId: 1234, state: "CA" }];
  const arr2 = [{ agentId: 1234, AK: "c", AL: "N", CA: "c" }];
  var res = [];
  arr1.forEach((x) => {
    arr2.forEach((y) => {
      if (x.agentId === y.agentId) {
        for (const [key, value] of Object.entries(y)) {
          if (value === "c") {
            x.state += " ," + key;
          }
        }
      }
    });
  });

結果應該是這樣的

arr1 = [{ agentId: 1234, state: "CA, AK" }]

您可以使用Array.reduce (和其中的Array.find來查找匹配的agentId )。 就像是:

 const arr1 = [{ agentId: 1234, state: "CA" }]; const arr2 = [{ agentId: 1234, AK: "c", AL: "N", CA: "c" }]; const arrCombined = arr1.reduce( (acc, val) => { const arr2Match = arr2.find(v => v.agentId === val.agentId); if (arr2Match) { return [...acc, {...val, ...arr2Match} ]; } return acc; }, []); console.log(arrCombined);

您可以使用Set來確保唯一性:

const arr1 = [
  { agentId: 1234, state: "CA" },
  { agentId: 4567, state: "FL" }
];
const arr2 = [
  { agentId: 1234, AK: "c", AL: "N", CA: "c" },
  { agentId: 4567, AK: "N", AL: "c", FL: "c" }
];

for (const x of arr1) {
  const states = new Set([x.state]);
  for (const y of arr2) {
    if (x.agentId === y.agentId) {
      for (const [key, value] of Object.entries(y)) {
        if (value === "c") {
          states.add(key);
        }
      }
      break;
    }
  }
  x.state = [...states].join(", ");
}

暫無
暫無

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

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