使用lodash转换对象的键和值的最优雅方法是什么?

时间:2015-10-23 23:34:51

标签: javascript object lodash

说我有以下对象:

 var Models = { User: ... 
    { collection: 
         { name: 'users' }
     } ...
    , Post: { ...
    collection: 
     { name: 'posts'
            }
        }
    }

我想把它变成:

 {'users': 'User', 'posts': 'Post'}

有没有人比这种方法(lodash)更优雅:

    collectionNames = _.mapValues(_.mapKeys(Models, function(model) {
    return model.collection.name;
}), function(model) {
    return model.modelName;
});

1 个答案:

答案 0 :(得分:1)

基本循环有什么问题,更容易理解,没有依赖关系?

  

的node.js

var Models = { User: {collection: { name: 'users' }}, Post: { collection: {name:'posts' }}
var res = {}
for (var key in Models) res[Models[key].collection.name] = key