-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"
  }
]
4
  • 3
    Where are you currently stuck at? Commented Nov 26, 2018 at 6:50
  • Hey, sorry about that, I wanna do it in Javascript Commented Nov 26, 2018 at 6:51
  • What did you try? Commented Nov 26, 2018 at 6:52
  • Convert the JSON to a JS Object and simply loop over each property and build your desired array of objects. Commented Nov 26, 2018 at 6:52

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

4 Comments

That is a first, we posted almost at the same time haha
Hey, thanks! This is exactly what I was looking for
@dladloti_liwa you can't accept both answers. You can only choose one to accept. However, you can upvote both answers.
@Ahmad Oh, okay cool. I'm a newbie here haha...
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)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.