sturoid
sturoid

Reputation: 2721

Create string from nested object with references to parent keys

I have an input like this:

{
 a: 'b',
  c: {
    d: 'e',
    f: {
      g: 'h',
      i: 'j'
    }
  }
}

How can I output a string like this where it creates a map down to the value of the last child on each initial key no matter how many levels deep:

'a=b&c[d]=e&c[f][g]=h&c[f][i]=j'

Upvotes: 0

Views: 70

Answers (1)

Jaromanda X
Jaromanda X

Reputation: 1

You are correct, recursion is required, along with Array methods like map and concat and join

var x = {
 a: 'b',
  c: {
    d: 'e',
    f: {
      g: 'h',
      i: 'j'
    }
  }
};
const makePath = (path, key) => path ? `${path}[${key}]` : `${key}`;
const doThings = (obj, path='') => 
    [].concat(...Object.entries(obj)
        .map(([key, value]) => 
            typeof value === 'object' ? doThings(value, makePath(path, key)) : `${makePath(path, key)}=${value}`
        )
    );

console.log(doThings(x).join('&'));

Upvotes: 1

Related Questions