遍历嵌套数组对象

时间:2020-04-13 04:32:07

标签: javascript arrays node.js object

我正在尝试遍历如下所示的嵌套数组对象。访问嵌套数组中每个对象元素的最佳方法是什么。

{
    "titleId": "111G",
    "aNumber": "1212",
    "data": [{
            "id": "6657",
            "name": "test name",
            "city": "LA",
            "state": "CA",
            "comment": "comment 1",
            "dates": [{
                    "startDate": "01/17/2020",
                    "endDate": "01/22/2020"
                },
                {
                    "startDate": "01/24/2020",
                    "endDate": "01/30/2020"
                }
            ]
        },
        {
            "id": "123",
            "name": "abc",
            "city": "NJ",
            "state": "NY",
            "comment": "comment 2",
            "dates": [{
                    "startDate": "01/17/2020",
                    "endDate": "01/22/2020"
                },
                {
                    "startDate": "01/24/2020",
                    "endDate": "01/30/2020"
                }
            ]
        }
    ]
}

我还需要访问数据和日期数组中的每个元素

2 个答案:

答案 0 :(得分:1)

如果我正确理解了这个问题,那么您想遍历数据项中每个项内部的dates数组,这就是我在js中要做的事情

var date = JSON.parse(res.data)

date.forEach(element => {
    var items =  element.dates
    items.forEach(current => {
        //do whatever 
    });
});

答案 1 :(得分:0)

    const info = {
    "titleId": "111G",
    "aNumber": "1212",
    "data": [{
            "id": "6657",
            "name": "test name",
            "city": "LA",
            "state": "CA",
            "comment": "comment 1",
            "dates": [{
                    "startDate": "01/17/2020",
                    "endDate": "01/22/2020"
                },
                {
                    "startDate": "01/24/2020",
                    "endDate": "01/30/2020"
                }
            ]
        },
        {
            "id": "123",
            "name": "abc",
            "city": "NJ",
            "state": "NY",
            "comment": "comment 2",
            "dates": [{
                    "startDate": "01/17/2020",
                    "endDate": "01/22/2020"
                },
                {
                    "startDate": "01/24/2020",
                    "endDate": "01/30/2020"
                }
            ]
        }
    ]
}
info.data.forEach(city => city.dates.forEach(cityDate => console.log(cityDate.startDate)))