Reputation: 45
I am working on some JSON parsing code, and I wanted to check if there are multiple "Addresses" blocks. In my example below there would be addresses[0] and addresses[1].
I could obviously just go by checking if I specifically want "LOCATION" or "MAILING", but is there a way to do something like
if address.length() > 1
or something along those lines?
"addresses" : [
{
"country_code" : "",
"country_name" : "",
"address_purpose" : "LOCATION",
"address_type" : "",
"address_1" : "",
"address_2" : "",
"city" : "",
"state" : "",
"postal_code" : "",
"telephone_number" : "",
"fax_number" : ""
},
{
"country_code" : "",
"country_name" : "",
"address_purpose" : "MAILING",
"address_type" : "",
"address_1" : "",
"address_2" : "",
"city" : "",
"state" : "",
"postal_code" : "",
"telephone_number" : "",
"fax_number" : ""
}
],
Upvotes: 0
Views: 215
Reputation: 4180
JSON is a data format, Javascript can parse it with JSON.parse()
and create a JS object out of it.
Then, depending on how your object is structured, you can apply/call any method on it, including array.length
Upvotes: 0
Reputation: 31421
Yes, since its an array you can indeed check the length of it:
let obj = {"addresses" : [
{
"country_code" : "",
"country_name" : "",
"address_purpose" : "LOCATION",
"address_type" : "",
"address_1" : "",
"address_2" : "",
"city" : "",
"state" : "",
"postal_code" : "",
"telephone_number" : "",
"fax_number" : ""
},
{
"country_code" : "",
"country_name" : "",
"address_purpose" : "MAILING",
"address_type" : "",
"address_1" : "",
"address_2" : "",
"city" : "",
"state" : "",
"postal_code" : "",
"telephone_number" : "",
"fax_number" : ""
}
]}
console.log(obj.addresses.length > 1)
Upvotes: 1