以角度2编程方式创建对象

时间:2017-06-12 05:42:11

标签: angular object typescript

我希望创建对象并通过typescript动态添加数据。

例如:

let data={
    "date":"27-5-2017",
    "name":"John"
};

这是我的初始对象。现在我想在主题中添加更多数据。

"Subject1":"20"
"Subject2":"30"

这个主题因学生而异。如何将此Subject添加到数据对象中。

4 个答案:

答案 0 :(得分:4)

将其定义为:

let data:any;

如果您已经初始化了json对象: 然后你可以直接使用

data['dynamic_key'] = value;

如果没有初始化并且想要第一次添加

data = {'dynamic_key' : value };

答案 1 :(得分:1)

你可以像这样直接分配。

data.Subject1 = "20"
data.Subject2 = "30"

答案 2 :(得分:1)

我会为此创建一个类。与通过data['subject1'] = 'math';data.subject1 = math等方法动态/手动添加属性相比,这样做的好处是确保属性名称不变。

class Student{

  public name: string;
  public dateOfEntry: string;
  public subjects: Array<Subject>;

  constructor(name: string, dateOfEntry: string){
    this.name = name;
    this.dateOfEntry = dateOfEntry;

    this.subjects = new Array<Subject>();
  }

  public addSubject(subject: Subject){
    // if we have not already added this subject to the list
    if(!this.subjects.find(val => val == subject))
      this.subjects.push(subject);
  }

}


class Subject{
    public name: string;

    constructor(name: string){
        this.name = name;
    }
}

然后当你想要一个新学生......

let bob: Student = new Student("bob", new Date().toString());
bob.addSubject(new Subject("Math")); // adds to list
bob.addSubject(new Subject("English")); // adds to list
bob.addSubject(new Subject("Math")); // WILL NOT ADD - already exists

答案 3 :(得分:0)

您可以直接X509Store certStore = new X509Store(StoreName.My, StoreLocation.CurrentUser); certStore.Open(OpenFlags.ReadOnly); X509Certificate2Collection certCollection = certStore.Certificates.Find( X509FindType.FindByThumbprint, "", false); // Get the first cert with the thumbprint if (certCollection.Count > 0) { X509Certificate2 cert = certCollection[0]; // Use certificate log.WriteLine(cert.FriendlyName); }