Answer the question
In order to leave comments, you need to log in
How to implement such a JS filter that filters products by property values of an associative array but in React?
I have a product filter:
HTML:
<!DOCTYPE html>
<html>
<head>
<title>Untitled</title>
<meta charset="utf-8">
<link rel="stylesheet" href="style.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="js/eshop.js"></script>
</head>
<body>
<div class="filter">
<div class="filter-inner">
<div class="dropdown">
<button onclick="myFunction()" class="dropbtn">Страна</button>
<div id="myDropdown" class="dropdown-content">
<button class="btn-filter">Все</button>
<input type="checkbox" class="btn" value="turkey"> Турция<br>
<input type="checkbox" class="btn" value="china"> Китай<br>
<input type="checkbox" class="btn" value="france"> Франция<br>
<input type="checkbox" class="btn" value="italy"> Италия<br>
</div>
</div>
</div>
</div>
<div id="goods"></div>
</body>
</html>
{
"11292" : {
"name" : "Платье1",
"cost" : 50,
"country" : "turkey",
"image" : "https://cdn.shopify.com/s/files/1/2671/4680/products/pol_dress_sage_240x.jpg?v=1553634712"
},
"11294" : {
"name" : "Платье2",
"cost" : 150,
"country" : "china",
"image" : "https://cdn.shopify.com/s/files/1/0519/8561/products/IMG_5881_76665333-5efd-46da-b57e-2472ddb55697_240x.jpg?v=1548397696"
},
"11295" : {
"name" : "Платье3",
"cost" : 200,
"country" : "france",
"image" : "https://cdn.shopify.com/s/files/1/0073/5671/1030/products/websizedphotos_1_copy_6_522fb324-3529-4e22-989e-0924860cb34d_240x.png?v=1553665976"
},
"11296" : {
"name" : "Платье4",
"cost" : 300,
"country" : "italy",
"image" : "https://cdn.shoptiques.com/shoptiques-shop/products/mock-neck-dress-14-blue-9f38a7d3_pl.jpg"
}
}
$(document).ready(function() {
var data;
function filterShow() {
var arr = [...document.querySelectorAll(".btn:checked")].map(({
value
}) => value);
var out = '';
for (var key in data) {
if (arr.length) {
var country = data[key].country;
if (!arr.includes(country)) continue;
}
out += '<div class="single-goods">';
out += '<h3>' + data[key]['name'] + '</h3>';
out += '<p>Цена: ' + data[key]['cost'] + '</p>';
out += '<img src="' + data[key].image + '">';
out += '<button class="add-to-cart" data-art="' + key + '">Купить</button>';
out += '</div>';
}
$('#goods').html(out);
}
function init() {
filterShow();
$(".btn").on("click", filterShow);
$(".btn-filter").on("click", function() {
$(".btn").prop("checked", false);
filterShow()
})
}
$.getJSON('goods.json', function(json) {
data = json;
init()
})
});
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question