【问题标题】:Change object value in array if the object id has own property in other object id [duplicate]如果对象ID在其他对象ID中具有自己的属性,则更改数组中的对象值[重复]
【发布时间】:2021-10-27 10:42:05
【问题描述】:

这是我的数据

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
  }
]

请帮助我。谢谢大家。

【问题讨论】:

  • 到目前为止你尝试了什么?

标签: javascript arrays validation object


【解决方案1】:

试试这个:

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

      您可以使用Array.map()Array.some() 来获得所需的结果。如果数组 b 中存在来自 a 的任何元素,则 Array.some() 将返回 true。

      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; }

      【讨论】:

      • 谢谢你,先生,你今天救了我! :)
      猜你喜欢
      • 2021-11-23
      • 2014-05-07
      • 1970-01-01
      • 2021-06-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-28
      相关资源
      最近更新 更多