-
回首忆惘然
利用jQuery.inArray()var productArray = res.products.filter(function(product) { return jQuery.inArray(tag, product.tags) !== -1;});var res = { products: [{ "id": 1, "title": "white shirt", "tags": [ "small", "medium", "large" ] }, { "id": 2, "title": "black shirt", "tags": [ "medium", "large" ] }, { "id": 3, "title": "blue shirt", "tags": [ "small", "medium", "large" ] } ]};tag = 'small';var productArray = res.products.filter(function(product) { return jQuery.inArray(tag, product.tags) !== -1;});console.log( productArray );<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
-
料青山看我应如是
你可以使用 JS(不是 jQuery)Array.prototype.filter()和Array.prototype.includes()const res = { products: [{ "id": 1, "title": "white shirt", "tags": [ "small", "medium", "large", ] }, { "id": 2, "title": "black shirt", "tags": [ "medium", "large", ] }, { "id": 3, "title": "blue shirt", "tags": [ "small", "medium", "large", ] } ]};const tag = "small";const productArray = res.products.filter(item => item.tags.includes(tag));console.log(productArray);以下是 jQuer 的.filter()功能及其工作原理的一个小提示:https ://api.jquery.com/filter/
-
肥皂起泡泡
警告:您的 json 格式错误。以下是正确的:{ "products": [ { "id": 1, "title": "white shirt", "tags": [ "small", "medium", "large" ] }, { "id": 2, "title": "black shirt", "tags": [ "medium", "large" ] }, { "id": 3, "title": "blue shirt", "tags": [ "small", "medium", "large" ] } ]}这是您要查找的代码:我们检查标签列表中包含我们想要的标签的每个产品。ajax 操作成功后调用filterProducts函数。出于演示目的,我剪切了 ajax 部分。const JSON_DATA = JSON.parse(`{"products":[{"id":1,"title":"white shirt","tags":["small","medium","large"]},{"id":2,"title":"black shirt","tags":["medium","large"]},{"id":3,"title":"blue shirt","tags":["small","medium","large"]}]}`);const TAG = "small";function filterProducts(json_products, tag) { if(json_products === undefined || tag === undefined) return []; return json_products.products.filter((product) => product.tags.includes(tag) );}console.log(filterProducts(JSON_DATA, TAG));