gpt4 book ai didi

javascript - 使用 jQuery 从 JSON 数组中获取唯一结果

转载 作者:可可西里 更新时间:2023-11-01 01:58:58 24 4
gpt4 key购买 nike

我有这段代码可以将数组中的“类别”显示到 JQuery 简单列表中。

它工作正常,但如果类别“篮球”中有 3 个项目,则该类别将出现 3 次。

我怎样才能让它们只出现一次?谢谢。

代码如下:

function loadCategories() {
console.debug('About to refresh with sort type : ' + sortType);
var items = [];

$.each(catalog.products,
function(index, value) {
items.push('<li id="' + index + '">' +
'<a data-identity="productId" href="./productList.page?category=' + value.category + '" >' +
'<p style="margin-bottom:0px;margin-top:0px;">' + value.category + '</p></a> </li>');
}
);

categoryView.html(items.join(''));
categoryView.listview('refresh');
}

这是我的数组的代码:

var catalog = {"products": [
{"id": "10001",
"name": "Mountain bike",
"color": "Grey/Black",
"long-desc": "12-speed, carbon mountain bike.",
"description": "",
"size": "20 inches",
"category": "Outdoors/ Equipment rental",
"sport": "Cycling",
"brand": "DaVinci",
"top-seller": ""},

{"id": "10002",
"name": "Pro Multi Basketball",
"color": "Rainbow",
"long-desc": "On sale this week only! This limited edition basketball is multi-coloured, and offers pro performance. Fun and games on the court!",
"description": "Limited edition basketball.",
"size": "N/A",
"category": "Team gear",
"sport": "Basketball",
"brand": "Nike",
"top-seller": "x"},

最佳答案

我不知道您的 products 数组是如何构建的(因此我的示例可能需要根据您的需要进行一些修改),但是您可以编写一小段代码来首先收集您的独特的类别到一个新的数组:

var categories = [];

$.each(catalog.products, function(index, value) {
if ($.inArray(value.category, categories) === -1) {
categories.push(value.category);
}
});

jsFiddle Demo

categories 将包含您需要的独特类别,您可以使用它来构建您的 HTML(不过要小心那些 li 元素的 ID,记住ID 不能重复,你可以给他们一个小前缀)。

关于javascript - 使用 jQuery 从 JSON 数组中获取唯一结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6680430/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com