简体   繁体   English

遍历字典以添加到另一个字典

[英]Iterating through a Dictionary to add to another

I am trying to loop through each value in my dictionary and then go out and get another dictionary based on one of the objects in the first dictionary through each loop iteration: 我试图遍历字典中的每个值,然后通过每次循环迭代,根据第一个字典中的一个对象获得另一个字典:

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

I'm not quite sure how to do this without an index. 我不太确定如何在没有索引的情况下执行此操作。 I need to increment through the dAlbumPhotos and append to the final dictionary that album and it's dAlbumPhotos 我需要增加dAlbumPhotos的数量并将其添加到最终词典中,即专辑和dAlbumPhotos

It looks like you're really using an Associative Array in Javascript so you should be able to change the last bit of your code to be: 看起来您实际上是在Java中使用关联数组,因此您应该可以将代码的最后一位更改为:

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

I think this is what you're after: 我认为这是您追求的目标:

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

A for..in loop gives you back the indexes, not the objects in the loop. for..in循环将为您提供索引,而不是循环中的对象。 That is, a.id is likely nonsensical -- you really mean dAlbums[a].id . 也就是说, a.id可能毫无意义-您的意思是dAlbums[a].id It follows that dAlbumsAndPhotos[a] is probably where you need to store the results. 因此, dAlbumsAndPhotos[a]可能是您需要存储结果的位置。

Suppose you have the photo data in a json table like this: 假设您将照片数据存储在json表中,如下所示:

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

Then you can use jOrder to extract the group index like this: 然后,您可以使用jOrder这样提取组索引:

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

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

This index will hold a dictionary with album names associated with the a list of ids of rows in dPhotos belonging to that album. 该索引将保存一个词典,该词典的专辑名称与属于该专辑的dPhotos中的行ID列表相关。

jOrder is available from http://github.com/danstocker/jorder jOrder可从http://github.com/danstocker/jorder获得

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM