UnderscoreJS - 如何使用迭代器之一展平对象?

时间:2014-04-23 13:21:21

标签: javascript jquery underscore.js

我想做一个面包屑。我从后端获得数据如下:

var object = {
    "Department": {
        "DeptCode": null,
        "Description": "123",
         "DeptName": {
              "name": "xyz"
         }
}}

使用下划线或jquery我想像这样修改对象:

var result = {
    "Department.DeptCode": null,
    "Department.Description": "123",
    "Department.DeptName.name": "xyz"
}

我尝试使用undrscore,但我没有得到任何结果。有没有人告诉我完成这项工作的可行方法?

我的尝试:

var lable = [];

_.each(object, function(key, obj){
    var title = obj;
    if(_.object(key)){
        _.each(key, function(text,obj){
            lable.push(title + '.' + obj + ':' + text);
        })
    }

});

console.log(lable);

Here is the fiddle

1 个答案:

答案 0 :(得分:2)

尝试创建一个递归函数,就像这样(基于你的小提琴):

var lable = {};

function flatten(object, title) {
    _.each(object, function(key, obj){
        var newTitle = obj;
        if (key != null && typeof(key)=='object') {
            flatten(key, (title) ? title + '.' + newTitle : newTitle);
        } else {
            lable[title + '.' + newTitle] = key;
        }
    });
};

flatten(object, '');

console.log(lable);

检查这个小提琴:http://jsfiddle.net/ACZs8/2/

另一种替代方法是用闭包替换全局变量方法,以定义更可重用的平面函数:

function flatten(mainObject) {
    var lable = {};
    flattenAux = function(object, title) {
        _.each(object, function(key, obj){
            var newTitle = obj;
            if (key != null && typeof(key)=='object') {
                flattenAux(key, (title) ? title + '.' + newTitle : newTitle);
            } else {
                lable[title + '.' + newTitle] = key;
            }
        });
    };
    flattenAux(mainObject, null);
    return lable;
}

var testResult = flatten(object);

console.log(testResult);

示例小提琴:http://jsfiddle.net/ACZs8/6/