Skip to content Skip to sidebar Skip to footer

Map `json String` To `tree` In Javascript

I am having JSON in the form of {'Others': null, 'Main Hobbies': {'Dance': ['Salsa', 'Solo'], 'Sports': ['Cricket']}, 'Game': ['PUBG', 'Cricket', 'Football']} ' And i want to conve

Solution 1:

You could take a recursive approach for objects by checking the type of the handed over data.

functioncreate(data, checked = false) {
    returnArray.isArray(data)
        ? data.map(name => ({ name, checked }))
        : Object
            .entries(data)
            .filter(([, v]) => v !== null && (!Array.isArray(v) || v.length))
            .map(([name, value]) => ({
                name,
                checked,
                children: create(value, checked)
            }))
}

var data = { empty: [], Others: null, "Main Hobbies": { Dance: ["Salsa", "Solo"], Sports: ["Cricket"] }, Game: ["PUBG", "Cricket", "Football"] },
    result = create(data);

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

Post a Comment for "Map `json String` To `tree` In Javascript"