user image

Shilpa
Published in : 2022-03-06

Required to convert Obj {} to Arr [] from key-value pairs using javascript

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?

Comments

Mohamed Atef Date : 2022-03-06

Best answers

51

Best answers

51

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 Date : 2022-03-06

Best answers

34

Best answers

34

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

Leave a comment

Join us

Join our community and get the chance to solve your code issues & share your opinion with us

Sign up Now

Related posts

Method refactoring to avoid to many npe checks
Publish date: 2022-03-05 | Comments: 0

Tag: Javascript

What is the use of package-lock JSON file?
Publish date: 2022-02-11 | Comments: 3

Tag: Javascript

Vanilla JavaScript Next & prev Navigation
Publish date: 2022-02-22 | Comments: 1

Tag: Javascript

jquery undefined function
Publish date: 2022-02-28 | Comments: 1

Tag: Javascript

javascript: Uncaught TypeError: undefined is not a function
Publish date: 2022-03-02 | Comments: 2

Tag: Javascript

Simple HTML date picker is showing not showing calendar icon!
Publish date: 2022-03-01 | Comments: 2

Tag: Javascript

JAVASCRIPT: How do I add another key to object?
Publish date: 2022-03-06 | Comments: 3

Tag: Javascript