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

Converting Object with nested keys into single object in Javascript

I want to convert this:

data: {
        "3": {
            name: ["Missing data for required field."],
        },
        "5": {
            id: ["Same id exist."],
        },
    }

into this:

data: [{
        key: "name",
        message: "Missing data for required field.",
        row: 3,
    },
    {
        key: "id",
        message: "Same id exist.",
        row: 5,
    },]

how to achieve this with just es6 syntax

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 :

You can do this with Object.entries:

const data = {
  "3": {
    name: ["Missing data for required field."]
  },
  "5": {
    id: ["Same id exist."]
  }
};

Object.entries(data).map(([a, b]) => {
  return {
    key: Object.keys(b)[0],
    message: Object.values(b)[0][0],
    row: a
  };
});

I’ve made some assumptions:

  1. There will only be one key in each object
  2. The value of the key will be an array with one string
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