2

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.

    });
});

1 Answer 1

4

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.