user image

Published in : 2022-03-06

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


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?


Rakshit Date : 2022-03-06

Best answers


Best answers


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

JavaScript variable for Changing CSS Height
Publish date: 2022-02-12 | Comments: 1

Tag: Javascript

Javascript Add (+) issue
Publish date: 2022-02-26 | Comments: 1

Tag: Javascript

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

Tag: Javascript

Javascript: Filtering arrays by it properties?
Publish date: 2022-03-05 | Comments: 1

Tag: Javascript

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

Tag: Javascript

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

Tag: Javascript