【问题标题】:Creating an array of objects using class in Typescript在 Typescript 中使用类创建对象数组
【发布时间】:2021-06-09 01:01:48
【问题描述】:

我正在重新设计此人的代码: https://stackblitz.com/edit/angular-sx79hu?embed=1&file=app/multiselect-autocomplete-example.html

所以我有一个用户类:

export class User {
  constructor(public code: string, public description: string, public selected: boolean ) {
    if (selected === undefined) selected = false;
  }
}

我还有另一个数组(NewArray),我将通过服务接收。它将是一个包含“i”个元素的对象数组,每个对象都有 props {"prop1":"value1", "prop2":"value2"}

我正在尝试创建一个名为 Users 的新数组,它将使用 User 类,但将通过循环 NewArray 来获取元素:

 users = [new User('i.prop1','i.prop2', false)]

但我只得到最后一个索引,而不是从 0 到 i 的所有索引。

我在这里缺少什么?谢谢!

【问题讨论】:

    标签: javascript arrays angular typescript object


    【解决方案1】:

    你需要使用类似下面的东西。检查并告诉我它是否有效。

    users = [];
    newArray.forEach((item, i) => {
        users.push(new User( item.prop1, item.prop2, false));
    }):
    

    【讨论】:

    • @Niramalya ....大声笑。我发誓我之前试过这个,但只得到了 1 个元素。但我现在试过了,它的工作方式正是我想要的。谢谢朋友!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-18
    • 2013-01-29
    • 2012-07-10
    • 1970-01-01
    • 1970-01-01
    • 2020-02-04
    相关资源
    最近更新 更多