Home > Software engineering >  How to make multidimensional object in Javascript / Jquery dynamically
How to make multidimensional object in Javascript / Jquery dynamically

Time:11-25

So I have this my initial data which i want to convert to multidimensional object according to the key,

var Data = {
    "1": "Hi 1",
    "1.1": "Hi 1.1",
    "1.1.1": "Hi 1.1.1",
    "2": "Hi 2",
    "2.1": "Hi 2.1",
    "2.2": "Hi 2.2",
    "3": "Hi 3",
}

1 contains 1.1

1.1 contains 1.1.1

2 contains 2.1 and 2.2

For example, My expected result:

NewData = {
    "1": {
        "Text": "Hi 1",
        "1": {
            "Text": "Hi 1.1",
            "1": {
                "Text": "Hi 1.1.1",
            },
        }, 
    },
    "2": {
        "Text": "Hi 2",
        "1": {
            "Text": "Hi 2.1",
        },
        "2": {
            "Text": "Hi 2.2",
        },
    },
    "3": {
        "Text": "Hi 3",
    },
}

What I have tried:

var NewData = {};
$.each(Data, function(key, value) {
    var splitted = key.split(".");

    $.each(splitted , function(key2, value2) {

        // Stuck here
        // How to make multidimensional object in Javascript dynamically.

    });
});

CodePudding user response:

You could reduce the path to the nested object and assign Text property.

const
    data = { "1": "Hi 1", "1.1": "Hi 1.1", "1.1.1": "Hi 1.1.1", "2": "Hi 2", "2.1": "Hi 2.1", "2.2": "Hi 2.2", "3": "Hi 3" },
    tree = Object
        .entries(data)
        .reduce((r, [path, text]) => {
            path
                .split('.')
                .reduce((o, k) => o[k] ??= {}, r)
                .Text = text;
                
            return r;
        }, {});

console.log(tree);
.as-console-wrapper { max-height: 100% !important; top: 0; }

  • Related