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

Convert key value object to array of objects

I have object key value in below format.

{
    "Code1": {
        "char10": "ch1",
        "number1": "1",
        "text1": "txt1"
    },
    "Code2": {
        "char2": "ch2",
        "num2": "2"
    },
    "Code3": {
        "text": "txt4"
    }
}

Would like to convert to this format :

{
  "Code1": [
    {
      "char10": "ch1",
      "number1": "1",
      "text1": "txt1"
    }
  ],
  "Code2": [
    {
      "char2": "ch2",
      "num2": "2"
    }
  ],
  "Code3": [
    {
      "text": "txt4"
    }
  ]
}

Managed to achieve to get somewhat similar response but not exact output which I am looking for.

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

Tried the below snippet but it returns diff format than expected.

Object.entries(payload).map((e) => ( { [e[0]]: e[1] } ))

Response with above snippet :

[
    {
        "Code1": {
            "char10": "ch1",
            "number1": "1",
            "text1": "txt1"
        }
    },
    {
        "Code2": {
            "char2": "ch2",
            "num2": "2"
        }
    },
    {
        "Code3": {
            "text": "txt4"
        }
    }
]

>Solution :

You could get all entries and map with wrapped values for a new object.

const
    data = { Code1: { char10: "ch1", number1: "1", text1: "txt1" }, Code2: { char2: "ch2", num2: "2" }, Code3: { text: "txt4" } },
    result = Object.fromEntries(Object
        .entries(data)
        .map(([k, v]) => [k, [v]])
    );

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
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