After I import the data as json from the detail page, in ProductDetail > brand > shoes > size.length get the length length is outputting in JSX.
But there is a problem. There are also products without shoes data for each detailed product on the detail page. I want to treat products without data as 0 instead of length as a ternary operator, but I don’t know how to handle it.
JavaScript
x
2
1
<p>{ProductDetail && ProductDetail.brand.shoes.size.length}</p>
2
But here, data without brand is used using the ternary operator.
<p>0</p> :
I want to display it like this.
JavaScript
1
4
1
Nike Air Force ProductDetail > brand > shoes > size > length(0,1,2,3,4,5,6) <p>{length}</p>
2
jordan shoes ProductDetail > brand > shoes > size > length(0,1,2,3,4,5) <p>{length}</p>
3
adidas shoes ProductDetail > brand > x -> Handles `<p>0</p>`.
4
Advertisement
Answer
If you need to show 0
when an object is null or parent object is null, Try some like below
JavaScript
1
2
1
<p>{ProductDetail?.brand?.shoes?.size?.length || 0}</p>
2
Basically with using optional chaining and ||
operator, The output will be
JavaScript
1
5
1
ProductDetail is null/undefined ==> 0
2
ProductDetail.brand null/undefined ==> 0
3
.
4
ProductDetail.brand.shoes.size has valid array ==> length
5
JavaScript
1
8
1
let ProductDetail = { brand: { shoes: { size: [2, 3] } } };
2
console.log(ProductDetail?.brand?.shoes?.size.length || 0);
3
4
ProductDetail = null;
5
console.log(ProductDetail?.brand?.shoes?.size.length || 0);
6
7
ProductDetail = { brand: { shoes: null } }
8
console.log(ProductDetail?.brand?.shoes?.size.length || 0);