Search code examples
javascriptarrayskeyjavascript-objects

How to convert object A to an array of objects with object A's properties and assign value and label to them


I have an object:

{
 "id": 12432,
 "application": "pashmodin",
 "unit": null,
 "status": "gholam",
 "issueDate": "1999-06-24T00:00:00",
 "description": "hasan"
}

I want it to become an array like:

[
  {"label": "id", "value": 12432},
  {"label": "application", "value": "pashmodin"},
  {"label": "unit", "value": null},
  {"label": "status", "value": "gholam"},
  {"label": "issueDate", "value": "1999-06-24T00:00:00"},
  {"label": "description", "value": "hasan"}
]

where each object has a label and a value assigned to them. How can I achieve it?


Solution

  • Using Object.entries() and map()

    const obj = {"id":12432,"application":"pashmodin","unit":null,"status":"gholam","issueDate":"1999-06-24T00:00:00","description":"hasan"}
    
    const res = Object.entries(obj).map(([label, value]) => ({label, value}))
    
    console.log(res)