array.push到数组中的数组

时间:2014-08-06 22:56:35

标签: javascript arrays node.js

我试图将JSON数据推送到数组中的数组。我可以发现与其他示例有问题的区别是两个数组都是由一个循环构建的,我认为这是我接收错误的原因。 TypeError: Cannot call method 'push' of undefined

这是我试图实现的一个极小的例子。

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'});
    }
}

我尝试创建的输出应该是这样的。

{
    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}
            ]
        }
    ]
}

测试节点是荒谬的,当然,但是不应该以这种方式添加它们吗?

3 个答案:

答案 0 :(得分:2)

该行:

json.trips.nodes.push({test: 'test'});

应该是:

json.trips[i].nodes.push({test: 'test'});

答案 1 :(得分:0)

json.trips.nodes确实未定义。我相信你想把它添加到trip循环中的新项目中?

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);
}

答案 2 :(得分:0)

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);

}