Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mutli-level nesting of objects in JavaScript

I want to write a function that takes a JavaScript object as input with selected attributes of the object and return a modified indented/grouping structure as shown below.

var s1 = {
    "f01":{},
    "f02":{},
    "f03":{},
    "f04":{},
    "f05":{}
};


var s2 = indent_items(s1, ["f02", "f03", "f04"]);

s2 should be structured this way

{
    "f01":{},
    "d01":{
        "f02":{},
        "f03":{},
        "f04":{}
    },
    "f05":{}
};


var s3 = indent_items(s2, ["f03", "f04"]);

s3 should be structured this way

{
    "f01":{},
    "d01":{
        "f02":{},
        "d02":{
            "f03":{},
            "f04":{}
        },
    },
    "f05":{}
};

and so on going deep many levels. How to achieve this?

like image 601
devlent Avatar asked May 28 '26 18:05

devlent


1 Answers

This solution features a recursion for the indentation.

  • Object.keys for getting all keys of the object
  • Array.prototype.forEach for iteration over the keys

function indent_items(obj, array) {

    function recursion(o, r) {
        Object.keys(o).forEach(function (k) {
            if (~array.indexOf(k)) {
                r[id] = r[id] || {};
                r[id][k] = o[k];
                return;
            }
            if (typeof o[k] === 'object') {
                r[k] = r[k] || {}
                recursion(o[k], r[k]);
                return;
            }
            r[k] = o[k];
        });
    }

    var result = {},
        id = 'd' + ('0' + ++count).slice(-2);

    recursion(obj, result);
    return result;
}

var count = 0,
    s1 = { "f01": {}, "f02": {}, "f03": {}, "f04": {}, "f05": {} },
    s2 = indent_items(s1, ["f02", "f03", "f04"]),
    s3 = indent_items(s2, ["f03", "f04"]);

document.write('<pre>s1:' + JSON.stringify(s1, 0, 4) + '</pre>');
document.write('<pre>s2:' + JSON.stringify(s2, 0, 4) + '</pre>');
document.write('<pre>s3:' + JSON.stringify(s3, 0, 4) + '</pre>');
like image 76
Nina Scholz Avatar answered May 30 '26 08:05

Nina Scholz