gpt4 book ai didi

javascript - 使用jquery获取与json对象中提供的值匹配的对象?

转载 作者:行者123 更新时间:2023-12-02 18:12:51 26 4
gpt4 key购买 nike

我有一个 json 对象,如下所示,并且我的 json 对象中有“skus”值的随机参数

喜欢

     var mytestvalue="Fit:Regular,Color:Coyote (120)"; or
var mytestvalue="Color:Coyote (120),Fit:Regular";


[
{
"index":0,
"title":"Foo1",
"skus":"Fit:Regular,Size:6,Color:Coyote (120)",
},
{
"index":1,
"title":"Foo2",
"skus":"Fit:Regular,Color:Coyote (120),Size:65",
},
{
"index":2,
"title":"Foo3",
"skus":"Fit:Regular,Size:7,Color:Coyote (120)",
},
{
"index":0,
"title":"Foo4",
"skus":"Color:Coyote (120),Fit:Regular,Size:7.5",
},
{
"index":1,
"title":"Foo5",
"skus":"Fit:Slim,Size:8,Color:Coyote (120)",
},
{
"index":2,
"title":"Foo6",
"skus":"Fit:Regular,Size:9,Color:Coyote (120)",
},
{
"index":0,
"title":"Foo7",
"skus":"Fit:Regular,Size:8.5,Color:Coyote (120)",
},
{
"index":1,
"title":"Foo8",
"skus":"Fit:Regular,Size:10,Color:Coyote (120)",
},
{
"index":2,
"title":"Foo9",
"skus":"Fit:Slim,Color:Coyote (120),Size:13",
},
{
"index":0,
"title":"Foo10",
"skus":"Fit:Regular,Size:8.5,Color:Coyote (120)",
},
{
"index":1,
"title":"Foo11",
"skus":"Fit:Regular,Size:10,Color:Coyote (120)",
},
{
"index":2,
"title":"Foo12",
"skus":"Fit:Regular,Color:Coyote (120),Size:13",
}
]

我编写了一个函数来获取 sku 与我拥有的变量的匹配组合

   function getSkuCombinations(obj,prodskuval) {
var combres = $.grep(obj, function (o) { //Will give you all the matches
return o.SKUOptions.indexOf(prodskuval) > -1;
});
return combres;
}

我这样称呼这个函数

     var combinationresults=getSkuCombinations(myobj,mytestvalue)

当我这样做时,我应该得到所有具有我通过的组合“mytestvalue”的sku,但这个函数现在只返回我

       var myresult= [{
"index":1,
"title":"Foo2",
"skus":"Fit:Regular,Color:Coyote (120),Size:65",
}]

谁能帮我做这件事

这个功能解决了我的问题,

     function getSkuCombinations(obj,prodskuval) {
var combres = $.grep(obj, function (o) { //Will give you all the matches
var newskus=o.skus.split(',').sort().join(',');
var newprdskus=prodskuval.split(',').sort().join(',');
return newskus.indexOf(newprdskus) > -1;
});
}

最佳答案

var checkSKU = function (obj, testValue) {
var results = [];
obj.forEach(function (item) {
if (item.skus.indexOf(testValue) > -1) {
results.push(item);
}
});
return results;
};

JSFiddle 测试用例:http://jsfiddle.net/N9V9q/3/

关于javascript - 使用jquery获取与json对象中提供的值匹配的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19569925/

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