如何使用underscore.js / lodash.js遍历集合

时间:2013-09-29 09:49:09

标签: collections underscore.js lodash

小问题。我有收藏品

var allnames = {
    'names': 
     [
         { 'name': [ {'surname': 'moe'}, {'nickname': 'moose' } ] },
         { 'name': [ {'surname':'larry'}, {'nickname': 'lark' } ] }
     ]
};

并希望访问/获取每个'surname''nickname'

我尝试了不同的选项而没有任何运气(例如_.each / _.map)。

有没有人在这方面有经验?

2 个答案:

答案 0 :(得分:5)

此代码段会将您拥有的结构转换为更易于使用的结构:

 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); }, {})
 });

这里的名称将是一个对象数组,每个对象都有一个姓氏和一个昵称:

[ { surname: 'moe', nickname: 'moose' }, { surname: 'larry', nickname: 'lark' } ]

一旦你有了这个结构,很容易操纵那个数组来提取你想要的东西,例如得到所有的姓氏:

var surnames = _.pluck(names, 'surname');
var nicknames = _.pluck(names, 'nickname');

答案 1 :(得分:0)

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