I have an array listOfFriends of objects that contain [{"name" : "fName lName", "uid" : "0102030405"}], ...
I want to cut down the size of this array , since I only need the uids , so I would like to make another array with only the uids
var listOfFriends, listOfFriendsUIDs;
//listOfFriends gets filled
for(var i = 0; i < listOfFriends.length; i++){
listOfFriendsUIDs[i].uid = listOfFriends[i].uid; // this line isn't working
//listOfFriendsUIDs is still undefined untill the start of this loop
}
asked Apr 3, 2013 at 14:39
Scott Selby
9,58012 gold badges63 silver badges97 bronze badges
3 Answers 3
You can use Array.prototype.map to create new array out of IDs:
var listOfFriendsUIDs = listOfFriends.map(function(obj) { return obj.uid; });
Check the browser compatibility and use shim if needed.
answered Apr 3, 2013 at 14:42
VisioN
146k35 gold badges287 silver badges291 bronze badges
Sign up to request clarification or add additional context in comments.
6 Comments
VisioN
@ScottSelby Yes, absolutely.
Scott Selby
that's some pretty sexy code :) , still learning js , thanks
Alnitak
@VisioN strictly speaking that's
Array.prototype.map - Array.map would be a (non-existent) class method, not an instance method.VisioN
@Alnitak Yes, I have used
Array.map just to be shorter.Alnitak
suggest you use
myArray.map or write it in full to avoid ambiguity |
Try to use projection method .map()
var listOfFriendsUIDs = listOfFriends.map(function(f){ return f.uid;});
Comments
listOfFriendsUIDs[i] is not defined, so you can't access its uid property. You either need:
// creates an array of UID strings: ["0102030405", ""0102030405", ...]
listOfFriendsUIDs[i] = listOfFriends[i].uid;
or
// creates an array of objects with a uid property: [{uid:"0102030405"}, ...]
listOfFriendsUIDs[i] = {}
listOfFriendsUIDs[i].uid = listOfFriends[i].uid;
answered Apr 3, 2013 at 14:42
apsillers
117k18 gold badges248 silver badges249 bronze badges
Comments
lang-js