Convert complex JavaScript object to dot notation object
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
Here is a fix/hack for 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);
};
You can use the NPM dot-object (Github) for transform to object to dot notation and vice-versa.
var dot = require('dot-object');
var obj = {
id: 'my-id',
nes: { ted: { value: true } },
other: { nested: { stuff: 5 } },
some: { array: ['A', 'B'] }
};
var tgt = dot.dot(obj);
Produces
{
"id": "my-id",
"nes.ted.value": true,
"other.nested.stuff": 5,
"some.array[0]": "A",
"some.array[1]": "B"
}