如何在Angular 6中将对象推入对象数组?

时间:2018-10-03 19:22:08

标签: javascript html angular angular2-forms

我有一个像groupList:any = {}这样的空对象数组,现在我想将一个对象推入其中。我正在尝试将名称和描述作为对象。

2 个答案:

答案 0 :(得分:4)

它不是数组,数组表示为[],可能您需要

groupList:any = [];

然后

this.groupList.push({name:'you',description:'what is array'});

答案 1 :(得分:0)

app.component.ts

declare var require: any;
import { Component } from '@angular/core';
import { OnInit } from '@angular/core';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent{
    groupList:any = [];
    arrayVal:any;
    currentVal : any;
  title = 'projectchart';
  public array = [{"id":1},{"id":3},{"id":5}];

 getPrev(){

     this.array.forEach((item, index) => {

  this.groupList.push(item.id);

});
console.log(this.groupList); 
 }


}

app.component.html

<button (click) ="getVal()">Previous Value</button>