【问题标题】:Importing Array to object - Angular 2+将数组导入对象 - Angular 2+
【发布时间】:2018-06-27 13:47:25
【问题描述】:

我的服务可以让我获得一系列类型:

ngOnInit() {
    this.coreService.getByType( this.name ).subscribe(
            response => { this.handleSuccess( response ); },
            error => { console.error( error ); });

}

handleSuccess( coreTypes ) {
    var data = [];
    var pushedItems = [];
    coreTypes.forEach( ( coreType ) => {
        var entriesForType = [];
        entriesForType.push( coreType );    
            if ( entriesForType.length > 0 ) {
                entriesForType.forEach( entry => this.data.push( entry ) );
                this.data = data;
            if (data.length > 0) {
                data.forEach( d =>  this.item.value = d && pushedItems.push(this.item));
            }
                if(this.gridOptions.api !== null){
                    this.gridOptions.api.setRowData( this.pushedItems );
                }
            } 
    });
}

目前,this.data 正在创建我这样的数组 this.data = ["one","two","three"]

我需要的是创建一个看起来像这样的对象数组

pushedItems = [{value:"one"},{value:"two"},{value:"three"}];

我定义了项目:对象;并在构造函数this.item = {value:""};

但是在函数中,当我设置this.item.value = d ...它一直向我显示错误“'Object'类型上不存在属性'值'...对实现像pushItems这样的数组有帮助吗?

【问题讨论】:

  • 在订阅者方法中使用这个subscribe( (response:any)=> { this.handleSuccess( response ); });

标签: arrays angular object


【解决方案1】:
handleSuccess() {
  const p = [];
  this.coreTypes.forEach(coretype => {
   let obj = {};
   obj[coretype] = coretype;
   p.push(obj);
  });
}

handleSuccess() {
  const p = [];
  this.coreTypes.forEach(coretype => {      
   p.push({coretypes:coretypes});
  });
}

【讨论】:

  • 纯代码答案不可能是好的答案。你能解释一下吗?
  • 第二个例子工作得很好......你可以输入 p.push({value: coretype});
【解决方案2】:

而不是将您的对象推送为:

arr.push(this.object);

你应该像这样推动它:

arr.push({
  value: this.object,
})

【讨论】:

    猜你喜欢
    • 2019-05-07
    • 1970-01-01
    • 1970-01-01
    • 2016-09-26
    • 2017-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-27
    相关资源
    最近更新 更多