Home > Net >  Convert nodes that consists of nested objects, strings, array into an unordered list (Javascript)
Convert nodes that consists of nested objects, strings, array into an unordered list (Javascript)

Time:06-22

I have this variable value of ["test", { testone: "check", filter: [{ testtwo: "ignore", cancel: ["3.2"]}]}, "testthree"].

What I want to do is to display this in an unordered list below.

 . test
   . check
       . ignore
         . 3.2
 . testthree

I can convert it to a list if its in an array or array object, nested kinda confused me. I am thinking that a recursive function (correct me if i am wrong) can be used here and this is my first time solving a complex problem with javascript, care to share some sample how to solve this? Thanks

CodePudding user response:

Here is a recursive function to produce a nested ul element. For the example data, there will be a sublist whose only item is a deeper list, and so you see two list bullets next to eachother. This is where the sample data has an array with one object-element -- without any "label".

function toUnorderedList(arr) {
    const ul = document.createElement("ul");
    let li = document.createElement("li");
    for (const value of Object.values(arr)) {
        if (Object(value) !== value) { // Primitive value
            li = document.createElement("li");
            li.textContent = value;
        } else { // Object (maybe Array)
            li.append(toUnorderedList(value));
        }
        ul.append(li);
    }
    return ul;
}

const data = [
    "test", 
    { 
        testone: "check", 
        filter: [
            { testtwo: "ignore", cancel: ["3.2"] }
        ], 
    },
    "testthree"
];

document.body.append(toUnorderedList(data));

  • Related