[SOLVED] How to parse object to array in TS?

Issue

This Content is from Stack Overflow. Question asked by BeginnerDev

I have to parse object like below:

const obj = {
    "package": {
        "dependencies": {
            "a": "b",
            "c": "d"
        }
    }
}

to this format:

const data = {
    "package": [
        {
            "dependencies": [
                { key: "a", value: "b" },
                { key: "c", value: "d" }
            ]
        }
    ]
}

Can someone tell me how to do this? Thanks for any help!



Solution

This is definitely possible. Without understanding the use case I feel that this sort of conversion might cause you more problems.
Anyhow the below is one way to achieve this.

const obj = {
    "package": {
        "dependencies": {
            "a": "b",
            "c": "d"
        }
    }
}

const packageArray = {
  package: [
    {
     dependencies: Object.entries(obj.package.dependencies)
      .map(([key, value]) => ({[key]: value}))
    }

]
  


This Question was asked in StackOverflow by BeginnerDev and Answered by adam.k It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?