I am currently attempting to flatten a json object with multiple embedded levels, here is an example of the original structure:
[
{
"one": 1,
"two": 2,
"three": [
{
"four": 4,
"five": 5
},
{
"six": 6,
"seven": 7
}
]
},
{
"one": 1,
"two": 2
}
]
My goal is to transform it into this desired result:
{
"0": {
"prefix[0]one": 1,
"prefix[0]three[0]five": 5,
"prefix[0]three[0]four": 4,
"prefix[0]three[1]seven": 7,
"prefix[0]three[1]six": 6,
"prefix[0]two": 2
},
"1": {
"prefix[1]one": 1,
"prefix[1]two": 2
}
}
I have found a script that successfully flattens the data, but I am looking for a way to group each top level array/object separately rather than combining them all into one large object.
The current code snippet I have been working on is below:
JSON.flatten = function(data) {
var result = {};
function recurse (cur, prop) {
if (Object(cur) !== cur) {
result[prop] = cur;
} else if (Array.isArray(cur)) {
for(var i=0, l=cur.length; i<l; i++)
recurse(cur[i], prop + "[" + i + "]");
if (l == 0)
result[prop] = [];
} else {
var isEmpty = true;
for (var p in cur) {
isEmpty = false;
recurse(cur[p], prop ? prop+p : p);
}
if (isEmpty && prop)
result[prop] = {};
}
}
recurse(data, "prefix");
return result;
}
The output of the current code snippet looks like this:
{
"prefix[0]one": 1,
"prefix[0]three[0]five": 5,
"prefix[0]three[0]four": 4,
"prefix[0]three[1]seven": 7,
"prefix[0]three[1]six": 6,
"prefix[0]two": 2,
"prefix[1]one": 1,
"prefix[1]two": 2
}
In an update, I realized my desired output should be structured differently, like so:
{
"0": {
"prefix[0][one]": 1,
"prefix[0][three][0][five]": 5,
"prefix[0][three][0][four]": 4,
"prefix[0][three][1][seven]": 7,
"prefix[0][three][1][six]": 6,
"prefix[0][two]": 2
},
"1": {
"prefix[1][one]": 1,
"prefix[1][two]": 2
}
}
After further exploration, I discovered that this new format would not fully work due to the nested objects. To address this, I am following suggestions from other developers and adopting a recursive approach to assign values as needed. Thank you for your input!