user

Shilpa

6 Mar 2022

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

6 Mar 2022

Best Answer

best answer

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.

 

 

 

© 2024 Copyrights reserved for web-brackets.com