0

What's an effective way to turn this:

{
  person:{
    name:'John',
    address:{
      city:'England',
      street:'99',
    }
  }
}

Into this:

{
  'person.name' :'John',
  'person.address.city':'England',
  'person.address.street':'99'
}

Thanks! Ps. I need it for updating mongo documents with multiple fields at the time without replacing the whole objects (using $set).

Slai
  • 22,144
  • 5
  • 45
  • 53
John
  • 13
  • 3
  • 1
    You mean like this? https://stackoverflow.com/questions/19098797/fastest-way-to-flatten-un-flatten-nested-json-objects – Kevin B Jun 07 '18 at 21:23
  • Thanks! now that I know the term, I can actually research it! – John Jun 07 '18 at 21:37

1 Answers1

0

Oversimplified example :

function flatten(object, result = {}, path) {
  if (!(object instanceof Object)) return result[path] = object;
  for (var key in object) flatten(object[key], result, path ? path + '.' + key : key); 
  return result;
}

console.log(flatten({ person:{ name:'John', address:{ city:'England', street:'99' }}}));

console.log( flatten( [[0]] ) );

console.log( flatten( 0 ) );
Slai
  • 22,144
  • 5
  • 45
  • 53