如何循环遍历另一个对象数组中的对象数组--javascript

时间:2015-10-30 11:05:33

标签: javascript arrays loops object

我的数据看起来像这样:

var songs = [
    {Object1: [{Obj1: songId}]},
    {Object2: [{Obj1: songId}]}
];

从整个歌曲阵列中获取所有songId的最佳方式是什么?

2 个答案:

答案 0 :(得分:2)

一些迭代会做。



var songs = [
        { Object1: [{ Obj1: 8 }] },
        { Object2: [{ Obj1: 99 }] }
    ],
    songId = [];

songs.forEach(function (o) {
    Object.keys(o).forEach(function (k) {
        o[k].forEach(function (a) {
            songId.push(a.Obj1);
        });
    });
});
document.write('<pre>' + JSON.stringify(songId, 0, 4) + '</pre>');
&#13;
&#13;
&#13;

答案 1 :(得分:1)

var songsIdCollection = [];

songs.forEach(function(wrappedSongData) {
    //{ Object1: [ {Obj1: songId} ] }
    wrappedSongData.forEach(function(songIdMaps) {
        //[ {Obj1: songId} ]
        songIdMaps.forEach(function(songIdMap) {
            //{Obj1: songId}
            songsIdCollection.push(songIdMap.Obj1);
        });
    });
});