迭代字典以添加到另一个字典

时间:2010-07-26 19:46:20

标签: javascript

我正在尝试遍历我的字典中的每个值,然后通过每次循环迭代出去并根据第一个字典中的一个对象获取另一个字典:

var dAlbumPhotos = {};  // holds a list of photo objects
var dAlbumsAndPhotos = {}; // will hold all the album | dAlbumPhotos for each album

for(var a in dAlbums)
{
    dAlbumPhotos = GetPhotosForAlbum(userID, accessToken, a.id);

    dAlbumsAndPhotos(a) = dAlbumPhotos;
}

如果没有索引,我不太清楚如何做到这一点。我需要通过dAlbumPhotos增加并附加到最​​后的字典那张专辑和它的dAlbumPhotos

4 个答案:

答案 0 :(得分:3)

看起来你真的在Javascript中使用了一个关联数组,所以你应该能够改变代码的最后一位:

for(var a in dAlbums)
{
    dAlbumPhotos = GetPhotosForAlbum(userID, accessToken, dAlbums[a].id);
    dAlbumsAndPhotos[a] = dAlbumPhotos;
}

答案 1 :(得分:2)

我认为这就是你所追求的:

var dAlbumPhotos = {};  // holds a list of photo objects
var dAlbumsAndPhotos = {}; // will hold all the album | dAlbumPhotos for each album

for(var a in dAlbums)
{
    dAlbumPhotos = GetPhotosForAlbum(userID, accessToken, dAlbums[a]);

    dAlbumsAndPhotos[a] = dAlbumPhotos;
}

答案 2 :(得分:0)

for..in循环为您提供索引,而不是循环中的对象。也就是说,a.id可能是荒谬的 - 你的意思是dAlbums[a].id。因此,dAlbumsAndPhotos[a]可能是您需要存储结果的地方。

答案 3 :(得分:0)

假设您在json表中有照片数据,如下所示:

var dPhotos = [{src: "/photos/a.jpg", album: "animals"}, {src: "/photos/b.jpg", album: "landscapes"}];

然后你可以使用jOrder来提取这样的组索引:

var table = jOrder(dPhotos)
    .index('album', ['album'], {grouped: true});

var index = table.index('album').flat();

此索引将包含一个字典,其中的相册名称与属于该相册的dPhotos中的行ID列表相关联。

jOrder可从http://github.com/danstocker/jorder

获取