在特定键下向数组添加条目

时间:2017-06-08 08:34:33

标签: javascript arrays

我正在循环一系列旅行,每次旅行都有一个End-Station。可以选择广泛的日期范围,以便同一End-Station有多次旅行。我的目标是增加另一个" date"到已经有End-Station条目的数组。

if(typeof(theResponse[current]) !== 'undefined') {
    for(var i=0; i < theResponse[current].length; i++) {

        var station = theResponse[current][i];
        Trips.push({
            EndStation: station.EndStationID, // Is the same for any theResponse[current][i]
            TripsOut: station.Tripcount,      // This should be added under the same "EndStation"
            Enabled: true,
            Trips: station.Trips
    })
    }
} else {
    console.log("sorry, no trips.");
}

例如:对于特定TripsOuttheResponse[current][1]可能为End-Station为5,对于同一终端,theResponse[current][2]SELECT * FROM table USE INDEX (cod_clie) WHERE cod_clie = "example" AND pwd_clie = "example" LIMIT 1; SELECT * FROM table WHERE cod_clie = "example" AND pwd_clie = "example" LIMIT 1; 为6。我如何添加这两个,以便在特定电台下有一个条目(在本例中为11)?目前,它会创建另一个条目,因此同一个终端站有多个条目。

1 个答案:

答案 0 :(得分:0)

我按照上述建议检查数组中是否已存在“终端站”,然后相应更新:

var station = theResponse[current][i];
var index = Trips.findIndex(x => x.EndStation == station.EndStation);
if(index !== -1) {
    Trips[index].TripsOut = Trips[index].TripsOut + station.Tripcount; // Add to existing value
    Trips[index].Trips.push(station.Trips); // Is an array, so push to append
} else {
    tripDetails.push({
        EndStation: station.EndStation,
        TripsOut: station.Tripcount,
        Enabled: true,
        Trips: station.Trips
    })
}