I have a javascript object in this form:
var order = {
"id": 13,
"name": "Sebastian",
"items": [
{
"id": 5
}
]
...
}
and I need to get this in a format that looks like this:
order[id] = 13
order[name] = "Sebastian"
order[items][0][id] = 5
What would be the best way to do this in Javascript? Are there any pre-built functions for this?
I'm on nodeJS with underscore and jquery.
There's probably a ready-made function out there, but this (quickly made) function should work too:
function convert(key, obj) {
var collector = {};
function recurse(key, obj) {
var property, name;
if( typeof obj === "object" ) {
for( property in obj ) {
if( obj.hasOwnProperty(property) ) {
name = key + "[" + property + "]";
recurse(name, obj[property]);
}
}
} else {
collector[key] = String(obj);
}
}
recurse(key, obj);
return collector;
}
Give it a starting key and the object, and you'll get a "flat" object back with full names and values:
var order = {
"id": 13,
"name": "Sebastian",
"items": [
{
"id": 5
}
]
};
var flattened = convert("order", order);
// `flattened` is now:
// {
// 'order[id]': 13,
// 'order[name]': 'Sebastian',
// 'order[items][0][id]': 5
// }