Sunday, June 2, 2024
 Popular · Latest · Hot · Upcoming
182
rated 0 times [  185] [ 3]  / answers: 1 / hits: 17075  / 12 Years ago, sun, november 4, 2012, 12:00:00

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.


More From » syntax

 Answers
150

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

[#82208] Friday, November 2, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
ignacio

Total Points: 467
Total Questions: 128
Total Answers: 79

Location: Luxembourg
Member since Tue, Mar 14, 2023
1 Year ago
ignacio questions
;