【问题标题】:How to push object into an object array in Angular 6?如何将对象推入 Angular 6 中的对象数组?
【发布时间】:2019-03-09 02:41:17
【问题描述】:

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

【问题讨论】:

标签: javascript html angular angular2-forms


【解决方案1】:

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

groupList:any = [];

然后,

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

【讨论】:

  • 是的,它不是一个数组,但我正在尝试使用角度形式将其推入以获得以下结构:"groupList": { {"name":group1","description":"descrption1"} }
  • @OliverQueen 您编写的 JSON 无效,您不能像这样在另一个对象中包含一个对象。对象由属性名称和值组成,因此您不能拥有这样的“未命名”属性。你是不是把它和字典混在一起了?例如"groupList": { "group1": "description1", "group2": "description2" }
【解决方案2】:

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>

【讨论】:

    猜你喜欢
    • 2023-03-29
    • 1970-01-01
    • 2017-12-05
    • 2016-05-09
    • 2016-12-25
    • 2020-02-08
    • 2019-03-24
    • 1970-01-01
    相关资源
    最近更新 更多