【问题标题】:Update array of objects property value on specific condition in angular在角度的特定条件下更新对象属性值数组
【发布时间】:2022-11-27 22:50:32
【问题描述】:

我从服务器返回了这个对象数组

{
    "Code": 200,
    "Message": "Success",
    "response": [
        {
            "UserId": null,
            "FullName": test,
            "Status": null,
            "IsActive": 1
        },
        {
            "UserId": null,
            "FullName": null,
            "Status": 'Active',
            "IsActive": 0
        }...
         ...
    ]
}

List变量中得到响应

 this.Service.getUser(payload).subscribe(result => {
          this.List = result['response'];
 });

我需要一些方法来操纵 Status 值,例如 Status 是 null 并为其分配 Active 值。

并再次将其存储在 this.List 变量中,而不使用任何循环。

请提出一些解决方案。

谢谢

【问题讨论】:

  • 我想知道你怎么能解决这个问题不使用任何循环.您必须遍历 response 数组。
  • @DecPK 是否有任何函数可以解决这个问题,或者我们可以在不影响性能的情况下使用循环

标签: javascript angular typescript


【解决方案1】:

由于响应对象是一个Array,你可以在它上面直接使用map{...user} 将使用现有对象的所有属性。只有Status 会被提供的逻辑覆盖。

this.List = result['response'].map((user) => ({...user, Status: user.status === null ? 'Active' : user.status}));

没有你就无法解决这个问题一些一种循环。这就是数组的本质。

【讨论】:

    【解决方案2】:

    你可以在这里使用map来遍历response数组并添加State作为Active如果Status === null

    const apiData = {
      "Code": 200,
      "Message": "Success",
      "response": [{
          "UserId": null,
          "FullName": 'test',
          "Status": null,
          "IsActive": 1
        },
        {
          "UserId": null,
          "FullName": null,
          "Status": 'Active',
          "IsActive": 0
        }
      ]
    }
    
    const result = apiData.response.map(o => ({ ...o, Status: o.Status ?? "Active" }));
    console.log(result);

    【讨论】:

    • 您的三元组缺少“其他”案例。除了那个不错的解决方案?
    • @PhilippMeissner 这不是三元运算符,而是我使用了null coalescing
    • 是的,既然您进行了正确的编辑 :)
    猜你喜欢
    • 1970-01-01
    • 2020-11-03
    • 2018-06-08
    • 2021-09-20
    • 1970-01-01
    • 2020-02-03
    • 1970-01-01
    • 2018-12-30
    • 2020-04-11
    相关资源
    最近更新 更多