代码之家  ›  专栏  ›  技术社区  ›  John Theoden

将数组导入对象-角度2+

  •  0
  • John Theoden  · 技术社区  · 7 年前

    我有一个服务可以让我获得类型数组:

    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正在创建这样的me数组 this.data = ["one","two","three"]

    我需要的是创建一个这样的对象数组

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

    i定义了项:对象;和在contstructor中 this.item = {value:""};

    但在功能上,当我设置 this.item.value = d ……它不断向我显示错误“属性”value“在类型”object“上不存在”…是否有助于实现类似pusheditems的数组?

    2 回复  |  直到 7 年前
        1
  •  2
  •   Jorge Monroy    7 年前
    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});
      });
    }
    
        2
  •  1
  •   dAxx_    7 年前

    而不是像这样推你的物体:

    arr.push(this.object);
    

    你应该像这样推它:

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