'Modify false values inside javascript object
Using the JSON file I am trying to build a product list.
There are cases where products don't have data (was price) and in this case I dont want to display anything.
If "was_price" is false I want to modify its property to an empty string ' ' but I cannot print it even if in console.log works.
{
"product_arr" : [
{
"name": "Example1",
"price": 40,
"was_price": false,
"reviews": 80,
"img": 1
}, {
"name": "Example2",
"price": 250,
"was_price": 300,
"reviews": 98,
"img": 2
}
]
}
fetch('./data/product.json')
.then(function (response) {
return response.json();
})
.then(function (data) {
appendData(data);
checkFalsePrice(data);
})
.catch(function (err) {
console.log(err);
});
function appendData(data) {
const html = data.product_arr.map(item =>
`<div class="product">
<div class="row">
<div class="col-sm-3 child">
<div class="row">
<div class="media"><img src="img/${item.img}.jpg" /></div>
</div>
<div class="row">
<div class="product-title">${item.name}</div>
</div>
<div class="row">
<div class="price"> £${item.price/100}</div>
</div>
<div class="row">
<div class="was-price"><span>Was</span> <span>${item.was_price/100}</span></div>
</div>
<div class="row">
<div class="reviews">${item.reviews}% Reviews Score</div>
</div>
</div>
</div>
</div>`)
document.getElementById("content").innerHTML = html.join("")
But return doesn't work
function checkFalsePrice(data) {
data.product_arr.map(function (arr) {
let wasPrice = arr.was_price;
if(wasPrice === false) {
return wasPrice.innerHTML = '';
} else {
return wasPrice;
}
})
}
<div id="content"></div>
Solution 1:[1]
dont use checkFalsePrice just try this
<div class="row">
<div class="was-price"><span>Was</span> <span>${item.was_price/100 || ''}</span</div>
</div>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | dangerousmanleesanghyeon |
