sf.
sf.

Reputation: 25480

Parse a flat Json list into a nested <ul> using Jquery

I'm trying to render a flat Json obect into a tree like <ul> using jquery.

This is what the Json object looks like

[
    {"FacetTypeId":1,"ProductId":22,"FacetName":"Gender","FacetSysName":"Gender","FacetTypeName":"Mens","FacetTypeSysName":"Mens"},
    {"FacetTypeId":6,"ProductId":22,"FacetName":"Size","FacetSysName":"Size","FacetTypeName":"157","FacetTypeSysName":"157"},
    {"FacetTypeId":7,"ProductId":22,"FacetName":"Size","FacetSysName":"Size","FacetTypeName":"158","FacetTypeSysName":"158"},
    {"FacetTypeId":15,"ProductId":22,"FacetName":"Size","FacetSysName":"Year","FacetTypeName":"2008","FacetTypeSysName":"2008"}
]

I'd like to create a nested ul like this:

<ul>
    <li>
        Gender
        <ul>
            <li>Mens</li>
        </ul>       
    </li>
    <li>
        Size
        <ul>
            <li>157</li>
            <li>158</li>
        </ul>       
    </li>
    <li>
        Year
        <ul>
            <li>2008</li>           
        </ul>       
    </li>
</ul>

Can anyone help point out the best way this could be achieved please?

Upvotes: 1

Views: 2927

Answers (1)

Tom Bartel
Tom Bartel

Reputation: 2258

You could use the JSON parser available from json.org to parse your string like this:

function parseJSON(s) {
    return JSON.parse(s, function (key, value) {
        var type;
        if (value && typeof value === 'object') {
            type = value.type;
            if (typeof type === 'string' && typeof window[type] === 'function') {
                return new (window[type])(value);
            }
        }
        return value;
    });
}

var arr = parseJSON(yourStringHere);

// Build object structure with FacetSysName as key
var categories = { }, current, cat;
for (var i = 0; i < arr.length; i++) {
    current = arr[i];
    cat = current.FacetSysName;
    categories[cat] = categories[cat] || [];
    categories[cat].push(current.FacetTypeName);
}

// Build ul element and append to body
var ulOuter = $('<ul></ul>'), ulInner, li, items;
for (cat in categories) {
    li = $('<li>' + cat + '</li>').appendTo(ulOuter);
    items = categories[cat];
    ulInner = $('<ul></ul>').appendTo(li);;
    for (var i = 0; i < items.length; i++) {
        ulInner.append($('<li>' + items[i] + '</li>'));
    }
}

$(body).append(ulOuter);

Upvotes: 3

Related Questions