user2935236
user2935236

Reputation: 189

Need Help in Convert Arrays of Objects into Single Array using Javascript

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.

Upvotes: 0

Views: 67

Answers (1)

Nina Scholz
Nina Scholz

Reputation: 386520

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; }

Upvotes: 2

Related Questions