【问题标题】:Using forEach in an array to find an object and change it's value in TypeScript在数组中使用 forEach 查找对象并在 TypeScript 中更改它的值
【发布时间】:2021-01-29 14:41:03
【问题描述】:

我有这样的声明:

private updateVariable(anId:number): void {

    this.model.forEach(q => 
        {
            q.anId === anId && (q.isUpdated = !q.isUpdated)
        });

模型定义为:

private model:Array<IMyData> = [];

IMyData 也是这样定义的:

export interface IMyData{
    anId:number;
    isUpdated:boolean;
}

目标是遍历数据以找到匹配的 anId 并且:

更改更新自:

null and false to true

来自:

true to false

提前致谢。

【问题讨论】:

  • 您对上述语句有任何错误吗?
  • 既然可以使用过滤器,为什么还需要使用 forEach?
  • @KiranShakya 这不是代码在做什么。
  • 如果你不介意把null改成false,你可以写q.isUpdated = q.isUpdated ^ (q.anId === anId)
  • 这段代码看起来不错,有什么问题吗?你没说是什么问题

标签: javascript arrays typescript ecmascript-6 foreach


【解决方案1】:

您可以改为在 1 行中完成。使用数组的.map()

const anId = '123';

this.model = this.model.map(item => item.anId === anId ? {...item, isUpdated: !item.isUpdated} : item)

console.log(this.model);     // to check the array with it's updated data

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-10-10
    • 2021-01-09
    • 2023-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-27
    • 1970-01-01
    相关资源
    最近更新 更多