简体   繁体   English

如何将这些javascript对象解析为分组的2d数组?

[英]How can I parse these javascript objects into a grouped 2d array?

New to javascript so trying to wrap my head around working with different data structures. javascript的新手,所以尝试用不同的数据结构来解决问题。

Got a collection of objects such as: 得到了对象的集合,例如:

{id:1234, photo:"pathtosomejpg"}
{id:1234, photo:"pathtosomejpg2"}
{id:1234, photo:"pathtosomejpg3"}
{id:2234, photo:"pathtosomejpg4"}
{id:2235, photo:"pathtosomejpg5"}

After I'm done looping I'd like to get a 2d array that has the id as the key, and the value is an array of all of the photo values that match that id. 循环完成后,我想获得一个以id为键的2d数组,其值是所有与该id匹配的photo值的数组。

Here's what I've tried: 这是我尝试过的:

var groupedImages = [];
var innerAlbumPhotos = [];

// foreach obj in collection
if groupedImages.hasOwnProperty(obj.id.toString())
 innerAlbumPhotos = groupedImages[obj.id.toString()];

innerAlbumPhotos.push(obj.photo);

groupedImages[obj.id.toString()] = innerAlbumPhotos;

How can I create the data structure described here? 如何创建此处描述的数据结构?

Try the following: 请尝试以下操作:

var results = [];
arr.forEach(function( v ) {
  var target = results[ v.id ];
  target 
    ? target.push( v.photo ) 
    : ( results[ v.id ] = [ v.photo ] );
});

Demo: http://jsfiddle.net/elclanrs/YGNZE/4/ 演示: http //jsfiddle.net/elclanrs/YGNZE/4/

I would use a loop for each element of the array. 我会为数组的每个元素使用一个循环。 If the id doesn't exist I create a new array for it and if the id exist I add the photo to it. 如果该ID不存在,则为其创建一个新数组;如果该ID存在,则将照片添加到其中。

var data = [{id:1234, photo:"pathtosomejpg"},
    {id:1234, photo:"pathtosomejpg2"},
    {id:1234, photo:"pathtosomejpg3"},
    {id:2234, photo:"pathtosomejpg4"},
    {id:2235, photo:"pathtosomejpg5"}];

var result = [];
for (var i = 0; i < data.length; i++) {
    if (result[data[i].id]) {
        result[data[i].id].push(data[i].photo);
    } else {
        result[data[i].id] = [data[i].photo];
    }
}

Arrays in javascript has no keys, so if you set arr[1000] = 1, the array will have 1000 elements. javascript中的数组没有键,因此,如果您设置arr [1000] = 1,则数组将具有1000个元素。 So you should use an object instead. 因此,您应该改用一个对象。

var photo_index = {};
function indexPhoto( photo_object ){
  if( !photo_index[photo_object.id] )
    photo_index[photo_object.id] = [];
  photo_index[ photo_object.id ].push( photo_object.photo );
}

Then, call indexPhoto for all your object formatted like you described. 然后,为所有格式如您所述的对象调用indexPhoto。

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

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