Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to unify an object from objects

good night, I’m having trouble merging an object inside another

my object currently.

{
   "id":7,
   "name":"Pedroo",
   "email":"pedro@hotmail.com",
   "cognitoSub":"9162b350-d19db1b3f",
   "phoneNumber":"+5521997221764",
   "photo":null,
   "createdAt":"2022-10-21T14:48:36.000Z",
   "updatedAt":"2022-10-21T14:48:36.000Z",
   "Account":{
      "userId":7
   }
}

and I would like to leave it in a single object

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

example:

{
   "id":7,
   "name":"Pedroo",
   "email":"pedro@hotmail.com",
   "cognitoSub":"9162b350-d19db1b3f",
   "phoneNumber":"+5521997221764",
   "photo":null,
   "createdAt":"2022-10-21T14:48:36.000Z",
   "updatedAt":"2022-10-21T14:48:36.000Z",
   "userId":7
}

>Solution :

Try this method

const flattenObj = (ob) => {

// The object which contains the
// final result
let result = {};

// loop through the object "ob"
for (const i in ob) {

    // We check the type of the i using
    // typeof() function and recursively
    // call the function again
    if ((typeof ob[i]) === 'object' && !Array.isArray(ob[i])) {
        const temp = flattenObj(ob[i]);
        for (const j in temp) {

            // Store temp in result
            result[j] = temp[j];
        }
    }

    // Else store ob[i] in result directly
    else {
        result[i] = ob[i];
    }
}
return result;
};
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading