Pregunta

I would like to make a breadcrumb. And I am getting a data from back end as like this:

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

And using underscore or jquery I would like to modify the object like this:

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

I tried using undrscore, but i am not get any result. any one show me the possible way to get this done?

my try:

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

¿Fue útil?

Solución

Try creating a recursive function, like this (based on your fiddle):

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

Check this fiddle: http://jsfiddle.net/ACZs8/2/

Another alternative, replacing the global variable approach with closures, to define a more reusable flatting function:

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

Example fiddle: http://jsfiddle.net/ACZs8/6/

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top