1

I worked nested object which I want to convert into recursive array or nested array.

I tried iterate the object something like below but it was creating single object of array.

Can anyone give suggestions or share your ideas it will helpful for me

        iterate(obj) {
                for (let property in obj) {
                  this.configArray.push({key: property,children: [], isValue: false, value: ''});
                    if (obj.hasOwnProperty(property)) {
                      const index = Object.keys(obj).indexOf(property);
                        if (typeof obj[property] == "object") {
                            this.iterate(obj[property]);
                        }
                        else {
                            this.configArray[index].children.push({ key: property, value: obj[property], isValue: true, children: [] });
                        }
                    }
                }
            }

INPUT

{
"Parent 1": {
    "11": "Child 1",
    "12": "Child 2",
},
"Parent 2": {
    "20": {
        "21": "Grand Child 1",
        "22": "Grand Child 2",          
    }
},
"Parent 3": {
    "31": "Child 1",
    "32": "Child 2",
}

}

OUTPUT

  [
{
    key: "Parent 1",
    value: "",
    children: [
        { key: 11, value: "Child 1", children: [] },
        { key: 12, value: "Child 2", children: [] }
    ]
},
{
    key: "Parent 2",
    value: "",
    children: [
        {
            key: 20,
            value: "",
            children: [
                { key: 21, value: "Grand Child 1", children: [] },
                { key: 22, value: "Grand Child 2", children: [] }
            ]
        }
    ]
},
{
    key: "Parent 3",
    value: "",
    children: [
        { key: 31, value: "Child 1", children: [] },
        { key: 32, value: "Child 2", children: [] }
    ]
},
];

1 Answer 1

3

You could take a recursive approach and map the value or the children, if value is an object.

function transform(object) {
    return Object
        .entries(object)
        .map(([key, value]) => Object.assign({ key }, value && typeof value === 'object'
            ? { value: '', children: transform(value) }
            : { value, children: [] }
        ));
}

var data = { "Parent 1": { 11: "Child 1", 12: "Child 2" }, "Parent 2": { 20: { 21: "Grand Child 1", 22: "Grand Child 2" } }, "Parent 3": { 31: "Child 1", 32: "Child 2" } },
    result = transform(data);

console.log(result);
.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.