推送后具有数组值的Javascript动态属性为空

时间:2019-01-25 22:59:19

标签: javascript angularjs typescript ionic3

这太疯狂了。我正在从Web服务器读取对象并对其进行循环,然后可以向该对象添加属性。但是,当我尝试自己制作新地图时,它不起作用。我能做到的很简单

// from the server and works
plans: any[];
sourceByPlan: any[];

// my own map for other purposes I try to fill
// as I loop through the items from the server
customMap: any[]; // also tried 'any'

var res = JSON.parse(response);
this.plans = res.plans; // where res.plans looks like [{value: "id", label: "readableid"}, {value: "id2", label: "otherreadable"}]
this.sourceByPlan = res.sources; // where res.sources looks like { id: [Object, Object, Object...]};

// loop through each source and add a property
for(var i = 0; i < this.plans.length; i++){
    if(this.sourceByPlan[this.plans[i].value]){
        for (var j = 0; j < this.sourceByPlan[this.plans[i].value].length; j++){
            var sObj = this.sourceByPlan[this.plans[i].value][j];

            var status = this.getStatus(sObj); // simple string
            sObj["newstatus"] = status; // THIS WORKS AS EXPECTED


            // here is where the new non working code starts
            var key = this.plans[i].value + status ; // looks like 'asdf1234pending'

            if (!customMap[key]) {
                customMap[key] = [];
            }

             customMap[key].push(sObj); // this will still be empty
        }   
    }
}

sObj不带有来自服务器的sObj.newstatus属性,但是它允许我根据需要添加它。我试图动态构建另一个地图,但是每次我检查console.log(customMap)时,它都是空的。从逻辑上讲,它看起来与我从服务器获取的对象相同。

1 个答案:

答案 0 :(得分:2)

您正在将未定义的对象推送到自定义地图。您可能要使用sObj:

customMap[key].push(sObj);