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
you can now use Optional chaining (?.) with ECMAScript 2020
sample code
const colletionjson = // just a name
{ collections:
[ { title : 'Home page'
, description : null
, image : null
}
, { title : 'Products'
, description : 'Products'
, image : { src : 'https:www.example.com' }
, products_count : 3
}
]
}
colletionjson.collections.forEach((collection, i) =>
{
let collectionTitle = collection.title
, collectionDescription = collection.description || ''
, collectionImage = collection.image?.src || ''
;
console.log (`index: ${i}, title: ${collectionTitle}, description: ${collectionDescription}, image: ${collectionImage}` )
})