Reputation: 41
Minor problem. I have the collection
var allnames = {
'names':
[
{ 'name': [ {'surname': 'moe'}, {'nickname': 'moose' } ] },
{ 'name': [ {'surname':'larry'}, {'nickname': 'lark' } ] }
]
};
and want to access/fetch each 'surname'
and 'nickname'
.
I have tried different options without any luck (e.g. _.each
/_.map
).
Is there anyone having experience in this area?
Upvotes: 0
Views: 2359
Reputation: 27976
This snippet will turn the structure you have there into something that's easier to work with:
var names = _.map( allnames.names, function(n){
// n is an array with each object having one property; either a surname or a nickname
return _.reduce(n.name, function(memo,part){ return _.extend(memo,part); }, {})
});
Here names will be an array of objects with each object having a surname and a nickname:
[ { surname: 'moe', nickname: 'moose' }, { surname: 'larry', nickname: 'lark' } ]
Once you have that structure it's easy to manipulate that array to extract what you want e.g. get all the surnames:
var surnames = _.pluck(names, 'surname');
var nicknames = _.pluck(names, 'nickname');
Upvotes: 5
Reputation: 41
I eventually found a solution, which covers what I was striving at
var allnames = {
'names':
[
{ 'name': [ {'surname': 'moe'}, {'nickname': 'moose' } ] },
{ 'name': [ {'surname': 'larry'}, {'nickname': 'lark' } ] }
]
};
var surnames = [];
var nicknames = [];
function nameproc(myobj)
{
if ( myobj.surname )
{
surnames.push(myobj.surname);
return myobj.surname
}
if( myobj.nickname)
{
nicknames.push(myobj.nickname);
return myobj.nickname;
}
}
_.each(allnames.names, function(myobj)
{
_.each(myobj, function(nameobj)
{
var nameobj = _.each(nameobj,nameproc);
});
});
// Print out the surnames and nicknames
console.log(surnames);
console.log(nicknames);
Upvotes: 0