gpt4 book ai didi

javascript - 如果数组中的值存在,如何获取数组。 jQuery

转载 作者:行者123 更新时间:2023-11-28 20:57:34 24 4
gpt4 key购买 nike

如果 "id":"236" 存在于 spConfig['attributs'][125]['options'] 中,则获取其中包含的数组。

你会如何在 jQuery 中做到这一点?

var spConfig = {
"attributes": {
"125": {
"id": "125",
"code": "pos_colours",
"label": "Colour",
"options": [{
"id": "236",
"label": "Dazzling Blue",
"price": "0",
"oldPrice": "0",
"products": ["11148"]
}, {
"id": "305",
"label": "Vintage Brown",
"price": "0",
"oldPrice": "0",
"products": ["11786", "11787", "11788", "11789", "11790", "11791", "11792", "11793"]
}]
}

}

最佳答案

您的数据结构稍微复杂,但假设 options.id 是唯一的,您可以使用

function foo(arg) {
var filtered;
$.each(spConfig.attributes, function() {
filtered = $(this.options).filter(function() {
return this.id == arg;
});
});
return (filtered.length) ? filtered[0].products : [];
}

Fiddle

当传递不存在的键时返回空数组的函数。

此外,如果您有多个 attribute 属性(125 除外)并且想要迭代它们:

function foo(arg) {
var filtered=[];
$.each(spConfig.attributes, function() {
filtered.push($(this.options).filter(function() {
return this.id == arg;
}));
});
filtered = $(filtered).filter(function() {
return this.length;
});
return (filtered.length) ? filtered[0][0].products : [];
}

Fiddle

或者,如果您始终访问属性attribute[125],为了简单起见,您也可以将其硬编码:

function foo(arg) {
var filtered = $(spConfig.attributes[125].options).filter(function() {
return this.id == arg;
});
return (filtered.length) ? filtered[0].products : [];
}

Fiddle

或者如果您需要更多自定义,则传递attribute属性名称。

function foo(arg, attr) {
var filtered = $(spConfig.attributes[attr].options).filter(function() {
return this.id == arg;
});
return (filtered.length) ? filtered[0].products : [];
}

Fiddle

关于javascript - 如果数组中的值存在,如何获取数组。 jQuery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11788961/

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