在Typescript中的Object中添加新值

时间:2017-03-14 11:01:45

标签: arrays json angular typescript

我在Angular 2 typescript

中编写了以下代码
import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
   myObj:any = 
   [
      { id: 11, name: 'Mr. Nice' },
      { id: 12, name: 'Narco' },
      { id: 13, name: 'Bombasto' },
      { id: 14, name: 'Celeritas' },
      { id: 15, name: 'Magneta' },
      { id: 16, name: 'RubberMan' },
      { id: 17, name: 'Dynama' },
      { id: 18, name: 'Dr IQ' },
      { id: 19, name: 'Magma' },
      { id: 20, name: 'Tornado' }
    ];
}

我想在myObj中插入新对象,如

      { id: 21, name: 'Doctor Strange' },
      { id: 22, name: 'New Hero' }

有人可以帮我解决这个问题吗?我不知道。

1 个答案:

答案 0 :(得分:2)

简单地推这样:

this.myObj.push(      
      { id: 21, name: 'Doctor Strange' },
      { id: 22, name: 'New Hero' });