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 object property parse to nested array array using javascript?

It receives data from the request body in the following format. Properly I have to insert it into the database but the format is not correct.

{
  name: '123',
  description: 'Dev',
  "item_variants[0]['name']": '23434',
  "item_variants[0]['quantity']": '12334',
  "item_variants[0]['unit_price']": '123123',
}

And how to transform the following format? Everyone’s answers help me some ideas. Thank you

{
      name: '123',
      description: 'Dev',
      item_variants: [
         {
            name: '23434',
            quantity: '23434',
            unit_price: '23434',
         }
      ]
}

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

>Solution :

In express, after getting this form body you have to store this response in any variable and reformate this response after formatting you can save it into the database.

try {
  let inputs = req.body;

  inputs = {
    name: inputs.name,
    description: inputs.description,
    item_variants: [
      {
        name: item_variants[0].name,
        quantity: item_variants[0].quantity,
        unit_price: item_variants[0].unit_price,
      },
    ],
  };

  // NOW you can save this formatted version into the database

  const result = await Product.save(inputs);
} catch (e) {
  console.log(e);
}

In item_variants name, quantity, unit_price you might change digging and getting value.

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