Shilpa
6 Mar 2022
Javascript
Hi, I want to convert objects JSON (Key-value pairs) to Array as given below,
My object JSON is given as below,
{"bookid": 1, "bookname": "rich dad poor dad", "issue_number": 1234}
I want output as,
[['bookid',1], ['bookname', 'rich dad poor dad'], ['issue_number',1234]]
Is It possible to achieve it?
You can do it using For loop of object like
let obj = {"bookid": 1, "bookname": "rich dad poor dad", "issue_number": 1234};
let arr = [];
for (const [key, value] of Object.entries(obj)) {
arr.push([key, value]);
}
Let me know if this works with you
Rakshit
6 Mar 2022
Best Answer
Using `Object.keys() ` and `map() `, you can convert your input as per your expected output.
See this working jsfiddle demo
Code:
var input = {"bookid": 1, "bookname": "rich dad poor dad", "issue_number": 1234};
var output = Object.keys(input).map((key) => [String(key), input[key]]);
alert(JSON.stringify(output));
//[["bookid",1],["bookname","rich dad poor dad"],["issue_number",1234]]
Reference: Mozilla Object keys, map
© 2024 Copyrights reserved for web-brackets.com