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 ?

6
  • 1
    Check this package: npmjs.com/package/dot-object Commented Jun 8, 2020 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. Commented Jun 8, 2020 at 22:55
  • 1
    What's the point? You have access to the properties. Commented Jun 8, 2020 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. Commented Jun 8, 2020 at 23:06
  • 1
    Found this: w3resource.com/javascript-exercises/fundamental/… (also, there's no such thing as a JSON object, JSON is a text format similar to/based on JS object literals) Commented Jun 8, 2020 at 23:11

1 Answer 1

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))
)

Sign up to request clarification or add additional context in comments.

1 Comment

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)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.