0

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.

4
  • 2
    1) Show us what you tried; 2) Show us the expected output. Commented Jul 30, 2018 at 11:01
  • I've updated my question. please check. Commented Jul 30, 2018 at 11:08
  • please add the output as valid array/object. Commented Jul 30, 2018 at 11:09
  • I think those all should be the string, I've updated my output array. Commented Jul 30, 2018 at 11:15

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

4 Comments

Wow, that's great, perfectly working. Thank you very much.
Little problem, when I am using this code on client server, it shows this error : Uncaught TypeError: array.reduce is not a function, any suggestion what can be the issue here?
where are you running it?
Sorry, the server took time to update the code. Everything is fine now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.