Convert object object to javascript lens object to point

I have an object like

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

I want to convert it to point notation (one level), for example:

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

I am currently converting an object manually using fields, but I think there needs to be a more general and general way for this. Whether there is a?

Note. There are several examples showing the return path, but I could not find the exact method.

Note 2: I want it to be used with an action binding with my server.

+8
javascript syntax
source share
3 answers

You can recursively add 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 a nested object, so do it again } else { res[newKey] = value; // it not an object, so set the property } } })(obj); var result = JSON.stringify(res); // convert result to JSON 
+18
source share

Here is a fix / hack when you get undefined for the first prefix. (I did)

 var dotize = dotize || {}; dotize.parse = function(jsonobj, prefix) { var newobj = {}; function recurse(o, p) { for (var f in o) { var pre = (p === undefined ? '' : p + "."); if (o[f] && typeof o[f] === "object"){ newobj = recurse(o[f], pre + f); } else { newobj[pre + f] = o[f]; } } return newobj; } return recurse(jsonobj, prefix); }; 
+4
source share

I wrote another function with a prefix function. I could not run your code, but I got a response. Thanks

https://github.com/vardars/dotize

 var dotize = dotize || {}; dotize.convert = function(jsonobj, prefix) { var newobj = {}; function recurse(o, p, isArrayItem) { for (var f in o) { if (o[f] && typeof o[f] === "object") { if (Array.isArray(o[f])) newobj = recurse(o[f], (p ? p + "." : "") + f, true); // array else { if (isArrayItem) newobj = recurse(o[f], (p ? p : "") + "[" + f + "]"); // array item object else newobj = recurse(o[f], (p ? p + "." : "") + f); // object } } else { if (isArrayItem) newobj[p + "[" + f + "]"] = o[f]; // array item primitive else newobj[p + "." + f] = o[f]; // primitive } } return newobj; } return recurse(jsonobj, prefix); }; 
+1
source share

All Articles