2017-06-08 4 views
0

私は一連の旅行をループしており、すべての旅行はEnd-Stationです。 End-Stationの複数の旅行があるように、広い日付範囲を選択することができます。私の目標は、別の「日付」から既に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."); 
} 

TripsOut特定End-StationためtheResponse[current][1] 5かもしれない、そしてそれは、同じエンドステーションのためtheResponse[current][2]ため6です。どのようにすればこれらの2つを追加して、特定のステーションの下に1つのエントリ(この場合は11)があるようにしますか?現在、別のエントリを作成しているため、同じエンドステーションのエントリが複数あります。

+1

検索を配列にして、代わりにプッシュするのでそれを更新存在する場合新しいもの?または、配列の代わりにオブジェクトを使用し、それぞれのプロパティのキーとして 'EndStationID'を使用して、検索するのではなく直接探すことができますか? – nnnnnn

+0

@nnnnnnありがとう! – ffritz

答えて

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 
    }) 
} 
関連する問題