-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"}
]
1
  • The key id, name are not always expected other values are also come in place let example: obj = {"id" : 1, "name": "John", age: "28''}; Commented Nov 4, 2019 at 9:45

2 Answers 2

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

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

Comments

0

You can try this:

JSON.stringify(
  Object.entries({"id" : 1, "name": "John"}).map(([key, value]) => ({
    key: key, 
    value: value
  }))
)

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.