I am trying to convert nested levels array of objects into a single array using a recursive function.
Below is my nested level json object that I need to convert into a single array
[{"CodiacSDK.NewModule.dll;extensionCreatePre;":[{"CodiacSDK.NewModule.dll;extensionExecutePost;":[{"CodiacSDK.PythonWrapper.dll;UnitValues::extensionInquirePre;":[]}]}]}]
I tried many recursive functions but none is working according to my requirement.
Like this one
function flatten(obj) {
var empty = true;
if (obj instanceof Array) {
str = '[';
empty = true;
for (var i=0;i<obj.length;i++) {
empty = false;
str += flatten(obj[i])+', ';
}
return (empty?str:str.slice(0,-2))+']';
} else if (obj instanceof Object) {
str = '{';
empty = true;
for (i in obj) {
empty = false;
str += i+'->'+flatten(obj[i])+', ';
}
return (empty?str:str.slice(0,-2))+'}';
} else {
return obj; // not an obj, don't stringify me
}
}
My expected output is
["CodiacSDK.NewModule.dll;extensionCreatePre;", "CodiacSDK.NewModule.dll;extensionExecutePost;", "CodiacSDK.PythonWrapper.dll;UnitValues::extensionInquirePre;"];
Any help is really appreciated. Thanks in advance.
You could use a recursive function for flattening the array of objects.
function getFlat(array) { return array.reduce( (r, o) => Object.entries(o).reduce((p, [k, v]) => [k, ...getFlat(v)], r), [] ); } var data = [{ "CodiacSDK.NewModule.dll;extensionCreatePre;": [{ "CodiacSDK.NewModule.dll;extensionExecutePost;": [{ "CodiacSDK.PythonWrapper.dll;UnitValues::extensionInquirePre;": [] }] }] }] console.log(getFlat(data));
.as-console-wrapper { max-height: 100% !important; top: 0; }
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.