简体   繁体   中英

Convert a simple Array to complex Object with items as child array

Using javascript ES6, I'm trying without success to get an easy algorithm to convert an array who contains a string, no size limit and I need as a result an object with array items as label and every item in a child array, depending on his position, kind of hard to explain,

Here is what I got "before" and what I want "after".

before = ["a","b","c","d"]

after = {
        name: "a"
        children: [
            {
                name: "b",
                children: [
                    {
                        name: "c",
                        children: [
                            name: "d"
                        ]
                    }
                ]
            }
        ]
    }

I'm totally blocked thanks for any help

You can use Array#reduceRight to create the structure from the array.

The reduceRight() takes an element from the end, wraps it with the object, and add the previous result into the children array. The children are assign conditionally using Object#assign , since the last object doesn't have children.

 const before = ["a","b","c","d"]; const after = before.reduceRight((r, name) => Object.assign({ name }, r !== null ? { children: [r] } : {}), null); console.log(after); 

Another answer, without using those fancy const and reduceRight stuff! =D

 var before = ["a","b","c","d"]; var after = createChildren(before); console.log(after); function createChildren(obj) { if (obj.length) { return { name: obj.shift(), children: [ createChildren(obj)] }; } return new Array(); } 

Shorter version:

 var before = ["a","b","c","d"]; var after = createChildren(before); console.log(after); function createChildren(obj) { return obj.length && { name: obj.shift(), children: [ createChildren(obj)] } || new Array(); } 

This is my solution:

 const after = ([name, ...rest], children = rest.length && [after(rest)]) => children ? { name, children } : { name }; const before = ['a', 'b', 'c', 'd']; console.log(JSON.stringify(after(before), null, 2)); 

This solution is similar to the one by Ori Dori, but it doesn't use Object#assign .

["a","b","c","d"].reduceRight((r, v, i) => {
    r.name = v;
    return i === 0 ? r : { children: [r] }
}, {});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM