-2

I am trying to restructure an object that I get from my API. See objects below.

{
  "App 1": "5a67-b-45-86e7-bfb351",
  "App 2": "293-e2-4a-96c-4471d0ea",
  "App 3": "f87d5-e0-41-bd-16dc72e"
}

I would like it to be reconstructed in the following format using Javascript:

I have the following data:

{
  "App 1": "5a67-b-45-86e7-bfb351",
  "App 2": "293-e2-4a-96c-4471d0ea",
  "App 3": "f87d5-e0-41-bd-16dc72e"
}

I would like it to be reconstructed in the following JSON format using Javascript:

[
  {
    "id" : "5a67-b-45-86e7-bfb351",
    "name" : "App 1"
  },
  {
    "id" : "293-e2-4a-96c-4471d0ea",
    "name" : "App 2"
  },
  {
    "id":"f87d5-e0-41-bd-16dc72e",
    "name":"App 3"
  }
]
trincot
  • 317,000
  • 35
  • 244
  • 286

2 Answers2

1

You can use Object.keys to obtain an array of all keys of your json object and then iterate through all keys and add them in the output array as such:

var data = {
      "App 1": "5a67-b-45-86e7-bfb351",
      "App 2": "293-e2-4a-96c-4471d0ea",
      "App 3": "f87d5-e0-41-bd-16dc72e"
  }
  
 var output = [];
 var keys = Object.keys(data);
 
 keys.forEach(function(key){
  var value = data[key];
  output.push({id:value,name:key});
 });
 
 console.log(output);
Ahmad
  • 12,336
  • 6
  • 48
  • 88
1

const obj = {
    "App 1": "5a67-b-45-86e7-bfb351",
    "App 2": "293-e2-4a-96c-4471d0ea",
    "App 3": "f87d5-e0-41-bd-16dc72e"
}

const newObj = []
Object.keys(obj).forEach(key => {
    newObj.push({ name: key, id: obj[key] }) 
})
console.log(newObj)