Flatten a Nested Object Into Dot Keys
Problem statement
You get a nested object written as text in a compact, JSON-like format:
- An object is
{, then zero or morekey:valuepairs separated by commas, then}. Keys are not quoted. - A value is another object, an integer, or one of the words
true,falseandnull.
Flatten it. For every value that is not an object, output one string path=value:
pathis the chain of keys from the outer object down to this value, joined with dots, for exampleuser.tags.admin.valueis written exactly as it appears intext.- An empty object
{}holds no values, so it produces nothing.
Return the strings in the order their values appear in text, from left to right.
Function
flattenObject(text: String) → String[]Examples
Example 1
text = "{user:{name:7,tags:{admin:true,beta:false}},id:42}"return = ["user.name=7","user.tags.admin=true","user.tags.beta=false","id=42"]Walk the object in order. user holds an object, so its keys get the prefix user.; tags inside it adds user.tags.. The top-level id has no prefix.
Example 2
text = "{a:{},b:null,c:{d:{}}}"return = ["b=null"]Empty objects hold no values, so a and c.d produce nothing. null is a value and is kept as written.
Example 3
text = "{}"return = []An empty object has nothing to list.
Constraints
2 <= text.length <= 5000textis one valid object in the format above, with no spaces.- Each key is 1 to 10 lowercase letters or digits, and keys inside one object are all different.
- Each integer is written without leading zeros (a lone
0is fine,-0is not) and is between-10^9and10^9. - Objects are nested at most 50 levels deep, counting the outer object.