Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to make multidimensional object in Javascript / Jquery dynamically

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

    });
});

>Solution :

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; }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading