New to javascript so trying to wrap my head around working with different data structures.
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.
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 ] );
});
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.
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. 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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.