user image

Shilpa
Published in : 2022-03-06

Help: How do I loop simple JSON objects to iterate all keys and values itself?

Javascript

I have an object as given below,

{"parking_space" : "16 X 25 FEET","parking_location" : "Address line items""parking_country" : "CA""parking_book_start_date": "03/06/2022 10:00:00","parking_book_start_date": "03/06/2022 20:30:00"}

I am using one Chart library, which is expecting an array format to be passed as DATA.

How do I convert these object keys to an array to pass as data in chart library?

Comments

Rakshit Date : 2022-03-06

Best answers

34

Best answers

34

There are two solutions to achieve your requirements.

 

#Solution 1 [Recommended]: Use Object.entries() - to convert object to array directly with one-liner question.

See live demo here

$( document ).ready(function() { var input = {"parking_space" : "16 X 25 FEET","parking_location" : "Address line items","parking_country":"CA","parking_book_start_date": "03/06/2022 10:00:00","parking_book_end_date":"03/06/2022 20:30:00"};var solution1 = Object.entries(input); console.log('Object.entries() ::: '+JSON.stringify(solution1));});
output: [["parking_space","16 X 25 FEET"],["parking_location","Address line items"],["parking_country","CA"],["parking_book_start_date","03/06/2022 10:00:00"],["parking_book_end_date","03/06/2022 20:30:00"]]

#Solution 2: Use Object.keys() - to get an array of all keys inside your object, iterate throughout all keys and get values. You need one array to manage keys and values according to your requirements. If your keys contains null values, you need a null check. inshort, this another solution is bit lengthy so I recommend to go with first solution,

 

Hope it will work for you.

 

 

 

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

How to toggle ( show and hide ) divs according to day hours?
Publish date: 2022-02-13 | Comments: 1

Tag: Javascript

How select specific tag in jQuery using if else statement?
Publish date: 2022-02-27 | Comments: 1

Tag: Javascript

How to open URL in new tab & focus on it in Javascript?
Publish date: 2021-12-22 | Comments: 1

Tag: Javascript

Can I read a local json, image or text file from Javascript?
Publish date: 2022-03-03 | Comments: 1

Tag: Javascript

How do I check if an array includes a value in JavaScript?
Publish date: 2022-02-13 | Comments: 2

Tag: Javascript