Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert complex JavaScript object to dot notation object

I have an object like

{ "status": "success", "auth": { "code": "23123213", "name": "qwerty asdfgh" } }

I want to convert it to dot notation (one level) version like:

{ "status": "success", "auth.code": "23123213", "auth.name": "qwerty asdfgh" }

Currently I am converting the object by hand using fields but I think there should be a better and more generic way to do this. Is there any?

Note: There are some examples showing the opposite way, but i couldn't find the exact method.

Note 2: I want it for to use with my serverside controller action binding.

like image 206
vardars Avatar asked Nov 04 '12 13:11

vardars


1 Answers

You can recursively add the properties to a new object, and then convert to JSON:

var res = {};
(function recurse(obj, current) {
  for(var key in obj) {
    var value = obj[key];
    var newKey = (current ? current + "." + key : key);  // joined key with dot
    if(value && typeof value === "object") {
      recurse(value, newKey);  // it's a nested object, so do it again
    } else {
      res[newKey] = value;  // it's not an object, so set the property
    }
  }
})(obj);
var result = JSON.stringify(res);  // convert result to JSON
like image 121
pimvdb Avatar answered Oct 02 '22 10:10

pimvdb