I'm trying to push JSON data to an array within an array. The problematic difference to other examples of this I can find is that both arrays are being built by a loop which I believe is the reason for the error I'm receiving. TypeError: Cannot call method 'push' of undefined
Here's a somewhat minimal example of what I'm trying to achieve.
var json = {origin: data.origin.name, destination: data.destination.name, trips: []};
for (var i = 0; i < data.trips.length; i++) {
var departure = data.trips[i].dep.time;
var arrival = data.trips[i].arr.time;
json.trips.push({departure: departure, arrival: arrival, nodes: []});
for (var j = 0; j < data.trips[i].legs.length; j++) {
json.trips.nodes.push({test: 'test'});
}
}
The output I'm trying to create should be looking like this.
{
origin: origin,
destination: destination,
trips: [
{
departure: departure,
arrival: arrival,
nodes: [
{test: test},
{test: test},
{test: test}
]
},
{
departure: departure,
arrival: arrival,
nodes: [
{test: test},
{test: test},
{test: test}
]
}
]
}
The test nodes are nonsensical, sure, but shouldn't adding them in this way be possible?
The line:
json.trips.nodes.push({test: 'test'});
should be:
json.trips[i].nodes.push({test: 'test'});
json.trips.nodes is indeed undefined. I believe you want to add it to the new item in the trip loop?
var json = {origin: data.origin.name, destination: data.destination.name, trips: []};
for (var i = 0; i < data.trips.length; i++) {
var newNode = {
departure: data.trips[i].dep.time,
arrival: data.trips[i].arr.time,
nodes: []
};
for (var j = 0; j < data.trips[i].legs.length; j++) {
newNode.nodes.push({test: 'test'});
}
json.trips.push(newNode);
}
var json = {origin: data.origin.name, destination: data.destination.name, trips: []};
for (var i = 0; i < data.trips.length; i++) {
var departure = data.trips[i].dep.time;
var arrival = data.trips[i].arr.time;
var trip = {departure: departure, arrival: arrival, nodes: []}
for (var j = 0; j < data.trips[i].legs.length; j++) {
trip.nodes.push({test: 'test'});
}
json.trips.push(trip);
}