问题
What would be the easiest way to convert the following key->value object "array" to a proper "JSON" style object? Example below would be converting input into graph.
var input = {
"graph.default.seriesColor" : ["#cccccc", "#3c3c3c"],
"graph.default.stackSeries" : false,
"graph.default.title.text" : "Hello!",
"graph.default.title.show" : false,
"graph.default.axesDefaults.show" : true,
"graph.default.axesDefaults.min" : 17,
"graph.default.axesDefaults.max" : 20,
};
var graph = {
default: {
seriesColor: ["#cccccc", "#3c3c3c"],
stackSeries: false,
title: {
text: "Hello!",
show: false
},
axesDefault: {
show: true,
min: 17,
max: 20
}
}
};
I considered using eval, however it quickly became complicated in a recursive way.
回答1:
For some reason I really felt like writing you a function for this:
function makeObj(input)
{
var output = {};
for(var key in input)
{
var nodes = key.split('.'), dest = output;
if(nodes.length < 1)
continue;
for(var i = 0; i < (nodes.length - 1); ++ i)
{
var node = nodes[i];
dest = (dest[node] === undefined) ?
(dest[node] = {}) : dest[node];
}
dest[nodes[nodes.length - 1]] = input[key];
}
return output;
}
graph = makeObj(input);
Obviously unlike an eval
solution, this will only accept strings in the exact format you described (x.y.z).
来源:https://stackoverflow.com/questions/11235906/convert-flattened-key-value-pairs-to-a-nested-object