-2

Need to create below output from the JSON obj

let obj = {"id" : 1, "name": "John"};

expected result:

[
  {key: "id", value: "1"},
  {key: "name", value: "John"}
]
Nick Parsons
  • 45,728
  • 6
  • 46
  • 64
  • The key id, name are not always expected other values are also come in place let example: obj = {"id" : 1, "name": "John", age: "28''}; – Amith TR Nov 04 '19 at 09:45

2 Answers2

0

You can try this:

JSON.stringify(
  Object.entries({"id" : 1, "name": "John"}).map(([key, value]) => ({
    key: key, 
    value: value
  }))
)
Dino
  • 7,779
  • 12
  • 46
  • 85
Puwka
  • 640
  • 5
  • 13
0

You can get the keys of obj using Object.keys() and map them to objects.

const obj = {
    "id": 1,
    "name": "John"
};
const result = Object.keys(obj).map(k => ({
    key: k,
    value: obj[k]
}));

console.log(result);
Rain336
  • 1,450
  • 14
  • 21