-3

How could i convert a json object from

{
  'data': {
    'x': {
      'y': 1
    }
  }
}

to

{
  'data': { 'x': { 'y': 1 } },
  'data.x': { 'y': 1 },
  'data.y': { 1 }
}

help is really needed :D

5
  • 2
    Your result output isn't even a valid object.
    – Marty
    Jul 14, 2020 at 4:44
  • Yes it is? what do you mean
    – Niiko
    Jul 14, 2020 at 4:46
  • 2
    They mean that it is indeed an invalid object
    – Alon Eitan
    Jul 14, 2020 at 4:47
  • @Niiko no this part { 1 } isn't Jul 14, 2020 at 4:50
  • Does this answer your question? List all possible paths using lodash
    – hgb123
    Jul 14, 2020 at 4:52

2 Answers 2

0

It is the bad way to handle json. I suggest a function get In lodash;

You can try

const ob = {
  'data': {
    'x': {
      'y': 1
    }
  }
}
_.get(ob, 'data')
_.get(ob, 'data.x')
_.get(ob, 'data.x.y')


0
0

If you mean

{
  'data': { 'x': { 'y': 1 } },
  'data.x': { 'y': 1 },
  'data.x.y': 1
}

You can do it with recursion:

const foo = {
  'data': {
    'x': {
      'y': 1
    }
  }
};


const loop = (obj, path, result) => {
  Object.entries(obj).forEach(([key, value]) => {
    result[`${path ? path + '.' : ''}${key}`] = JSON.parse(JSON.stringify(value));
    if(typeof value === 'object') {
      loop(value, `${path ? path + '.' : ''}${key}`, result); 
    }
  });
  return result;
}

const result = loop(foo, '', {});

console.log(result);

1
  • Was what i was looking for at the start but found out that lodash works way better, thanks anyways!
    – Niiko
    Jul 14, 2020 at 6:02

Not the answer you're looking for? Browse other questions tagged or ask your own question.