Home > Software engineering >  How to parse object to array in TS?
How to parse object to array in TS?

Time:09-18

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!

CodePudding user response:

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}))
    }

]
  

CodePudding user response:

Something like that should work :

const data = {...obj} // Copy the initial object
data.package.dependencies= Object.entries(obj.package.dependencies)
    .map(([key, value])=>({key,value}))

CodePudding user response:

As already pointed out, Object.entries Array.prototype.map will give desired transformation:

const obj = {
    "package": {
        "dependencies": {
            "a": "b",
            "c": "d"
        }
    }
};
const data = {
    package: {
        dependencies: Object.entries(obj.package.dependencies).map(([key, value]) => ({key, value}))
    }
};
console.log(JSON.stringify(data, null, "  "));

Output:

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

TypeScript playground link here

  • Related