1

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

2
  • Are you open to using recursion? Commented Dec 20, 2017 at 19:17
  • Yes i don't know so much about that actually .. Commented Dec 20, 2017 at 19:19

4 Answers 4

2

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);

Sign up to request clarification or add additional context in comments.

Comments

1

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));

Comments

1

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] }
}, {});

Comments

1

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();
}

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.