I have this JSON I retrieve from an API that contains null values. How do I better traverse the JSON and abstract the functionality?
const colletionjson =
{ "collections":
[ { "title" : "Home page"
, "description" : null
, "image" : null
}
, { "title" : "Products"
, "description" : "Products"
, "image" : { "src": "https:www.example.com" }
, "products_count" : 3
}
]
}
$.each(collectionjson, function (key, value) {
$.each(value, function (key, value) {
var collectionTitle = value.title;
var collectionDescription = value.description;
if (value == "image" && $.isArray(value)) {
var collectionImage = value.image.src;
} else {
var collectionImage = "";
}
});
});
// Do something with the data
2
Answers
you can now use Optional chaining (?.) with ECMAScript 2020
sample code