2

There is an JSON object I have:

{
  "inputs": {
    "country": "TR",
    "isActive": true,
    "person": {
      "fullName": "Şeref Can Muştu"
    }
  }
}

I want this JSON object like this:

{
    "inputs.country": "TR",
    "inputs.isActive": true,
    "inputs.person.fullName": "Şeref Can Muştu"
}

Is there an easiest way to make it with lodash or any most common library or just an easy method which is usable ?

canmustu
  • 2,304
  • 4
  • 21
  • 34
  • 1
    Check this package: https://www.npmjs.com/package/dot-object – Elias Soares Jun 08 '20 at 22:55
  • 1
    I wouldn't think this is a common enough thing to warrant a lodash function. It's more of a use case for a tree walking algorithm. – Taplar Jun 08 '20 at 22:55
  • 1
    What's the point? You have access to the properties. – StackSlave Jun 08 '20 at 23:04
  • @StackSlave I have to get them as string format. It is necessary for an API which uses Mongo. Vice versa, It updates and overrides whole object. – canmustu Jun 08 '20 at 23:06
  • 1
    Found this: https://www.w3resource.com/javascript-exercises/fundamental/javascript-fundamental-exercise-233.php (also, there's no such thing as a JSON object, JSON is a text format similar to/based on JS object literals) –  Jun 08 '20 at 23:11
  • @ChrisG Thx Chris, that is absolutely what I want. – canmustu Jun 08 '20 at 23:16

1 Answers1

1

flatMap to merge, recursively build key string in dotkey parameter, emit [dotkey, value] when non-object is found.
Object.fromEntries to merge into one object map.

data={
  "inputs": {
    "country": "TR",
    "isActive": true,
    "person": {
      "fullName": "Şeref Can Muştu"
    }
  }
}


walk = (node, dotkey) => 
   Object.entries(node).flatMap(([key,value]) =>
     typeof value === 'object' ?
       walk(value, (typeof dotkey !== 'undefined' ? dotkey + '.' : '') + key) :
       [[dotkey+'.'+key,value]])

console.log(
Object.fromEntries(walk(data))
)
user120242
  • 14,918
  • 3
  • 38
  • 52
  • If you want invalid property accessor keys to use bracket notation (eg: obj.prop1['key ; "\'invalid']) use a regex to scan the key and escape it) – user120242 Jun 08 '20 at 23:34