I’m trying to populate a div dynamically with data from JSON but want to avoid duplicates. The script below will give me 3 divs, 2 “standard” and one “special”.
How can I achieve without creating duplicate div?
var productList = [
{
model:"helskap",
type:"special",
family:"Bravo"
},
{
model:"Z-skap",
type:"standard",
family:"Valhalla"
},
{
model:"smafacksskap",
type:"standard",
family:"Jona"
}
];
$.each(productList, function(i, item) {
$('.filter').append('<div class="' + productList[i].type+ '"><input type="radio" name="type" value="' + productList[i].type+ '" /><label>' + productList[i].type+ '</label></div>')
});
<div class"filter"></div>
Advertisement
Answer
The better way is to first get the array with unique objects on property type then you can use that new filtered array for rendering like in filterProductList:
var productList = [{
model: "helskap",
type: "special",
family: "Bravo"
},
{
model: "Z-skap",
type: "standard",
family: "Valhalla"
},
{
model: "smafacksskap",
type: "standard",
family: "Jona"
}
];
var filterProductList = productList.reduce((acc, item) => {
var existItem = acc.find(({type}) => type === item.type);
if (!existItem) {
acc.push(item);
}
return acc;
}, []);
console.log(filterProductList);Then use filterProductList to render the HTML in your page. Your code will look:
$.each(filterProductList, function(i, item) {
var type = filterProductList[i].type;
$('.filter').append('<div class="' + type + '"><input type="radio" name="type" value="' + type + '" /><label>' + type + '</label></div>')
});