如果对象 ID 在其他对象 ID 中有自己的 属性,则更改数组中的对象值

Change object value in array if the object id has own property in other object id

这是我的数据

let a = [
  {
    "activityCode": "23",
    "isValid": null
  },
  {
    "activityCode": "28",
    "isValid": null
  },
  {
    "activityCode": "32",
    "isValid": null
  }
]

let b = [
  {
    "activityCode": "23",
    "allocated": 3
  },
  {
    "activityCode": "32",
    "allocated": 2
  }
]

如果数组中的 activityCode(a) 具有相同的 activityCode(b),我想将“isValid”更改为 true;如果数组中的 activityCode(a) 具有不同的 activityCode(b),则“isValid”更改为 false,我需要这样的输出:

let a = [
  {
    "activityCode": "23",
    "isValid": true
  },
  {
    "activityCode": "28",
    "isValid": false
  },
  {
    "activityCode": "32",
    "isValid": true
  }
]

请帮帮我。谢谢大家。

a.map(aa => {
  const match = b.find(bb => bb.activityCode === aa.activityCode);
  return { activityCode: aa.activityCode, isValid: match !== undefined };
})

试试这个:

a.forEach(element => {
  element.isValid = b.some(e => e.activityCode === element.activityCode);
});
console.log(a);

您可以使用 Array.map()Array.some() 来获得想要的结果。如果数组 b 中存在来自 a 的任何元素,Array.some() 将 return 为真。

let a = [ { "activityCode": "23", "isValid": null }, { "activityCode": "28", "isValid": null }, { "activityCode": "32", "isValid": null } ]
let b = [ { "activityCode": "23", "allocated": 3 }, { "activityCode": "32", "allocated": 2 } ]

const result = a.map(({ activityCode }) => ({ activityCode, isValid: b.some(el => el.activityCode === activityCode ) }));
console.log('Result:', result)
.as-console-wrapper { max-height: 100% !important; top: 0; }