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?
JavaScript
x
19
19
1
var productList = [
2
{
3
model:"helskap",
4
type:"special",
5
family:"Bravo"
6
},
7
{
8
model:"Z-skap",
9
type:"standard",
10
family:"Valhalla"
11
},
12
{
13
model:"smafacksskap",
14
type:"standard",
15
family:"Jona"
16
}
17
18
];
19
JavaScript
1
4
1
$.each(productList, function(i, item) {
2
$('.filter').append('<div class="' + productList[i].type+ '"><input type="radio" name="type" value="' + productList[i].type+ '" /><label>' + productList[i].type+ '</label></div>')
3
});
4
JavaScript
1
2
1
<div class"filter"></div>
2
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
:
JavaScript
1
27
27
1
var productList = [{
2
model: "helskap",
3
type: "special",
4
family: "Bravo"
5
},
6
{
7
model: "Z-skap",
8
type: "standard",
9
family: "Valhalla"
10
},
11
{
12
model: "smafacksskap",
13
type: "standard",
14
family: "Jona"
15
}
16
17
];
18
19
var filterProductList = productList.reduce((acc, item) => {
20
var existItem = acc.find(({type}) => type === item.type);
21
if (!existItem) {
22
acc.push(item);
23
}
24
return acc;
25
}, []);
26
27
console.log(filterProductList);
Then use filterProductList
to render the HTML in your page. Your code will look:
JavaScript
1
5
1
$.each(filterProductList, function(i, item) {
2
var type = filterProductList[i].type;
3
$('.filter').append('<div class="' + type + '"><input type="radio" name="type" value="' + type + '" /><label>' + type + '</label></div>')
4
});
5