0

小问题。我有收藏

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

并且想要访问/获取每个'surname''nickname'.

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

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

4

2 回答 2

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');
于 2013-09-29T11:21:29.490 回答
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);
于 2013-09-30T23:31:46.453 回答