Home > Software engineering >  How to convert string array into custom nested object
How to convert string array into custom nested object

Time:09-29

I am trying to convert a string array into single nested object suggest a best way to do that,

For example, If I had a single element in an array

Input:

var keys = ["A"];

It should be like this,

Output:

{
    and: {
        tags: {
            contains: "A"
        }
    }
}

And if I add a second element for example,

Input:

var keys = ["A","B"];

It should add as a nested object like this,

Output:

{
    and: {
        tags: {
            contains: "A"
        },
        and: {
            tags: {
                contains: "B"
            }
        }
    }
}

CodePudding user response:

You can try to use Array.reduceRight function(Thanks Drew Reese's suggestion):

const nest = arr => arr.reduceRight((acc, cur) => ({ and: { tags: { contains: cur }, ...acc } }), {});

console.log(nest(['A']));
console.log(nest(['A', 'B']));
console.log(nest(['A', 'B', 'C']));

  • Related