gpt4 book ai didi

javascript - 检查 JSON 数据中是否存在多个键值对

转载 作者:行者123 更新时间:2023-12-03 02:23:19 24 4
gpt4 key购买 nike

我有多个产品格式化的 JSON 数据,每个产品都有多个变体,并且数据显示变体是否可用以及变体的大小。

 "products":[  
{
"variants":[
{
"available":true,
"selectedOptions":[
{
"name":"Size",
"value":"M"
}
]
},
{
"available":true,
"selectedOptions":[
{
"name":"Size",
"value":"L"
}
]
}
]
},
{
"variants":[
{
"available":true,
"selectedOptions":[
{
"name":"Size",
"value":"S"
}
]
},
{
"available":false,
"selectedOptions":[
{
"name":"Size",
"value":"L"
}
]
}
]
}
]

我想遍历 JSON 数据并判断产品变体的大小是否很大(“value”:“L”)以及产品是否可用(“available”:true)。我可以检查其中之一,但我不确定如何同时检查两者。这是我到目前为止所拥有的:

o = products;    
function traverse(o) {
for (var i in o) {
if(o[i] == true){
console.log([i,o[i]]);
}
if(o[i] == 'L'){
console.log([i,o[i]]);
}
if (o[i] !== null && typeof(o[i])=="object") {
traverse(o[i]);
}
}
}
console.log(o);
traverse(o);
}

最佳答案

您可以使用此方法循环遍历每个产品的可能变体,并根据可用性和尺寸确定目标。

此方法使用函数 findforEach 来遍历对象。

函数 find 查找大小为 LselectedOption 和嵌套的 forEach 以检查可用性。

var obj = {  "products": [{      "variants": [{          "available": true,          "selectedOptions": [{            "name": "Size",            "value": "M"          }]        },        {          "available": true,          "selectedOptions": [{            "name": "Size",            "value": "L"          }]        }      ]    },    {      "variants": [{          "available": true,          "selectedOptions": [{            "name": "Size",            "value": "S"          }]        },        {          "available": false,          "selectedOptions": [{            "name": "Size",            "value": "L"          }]        }      ]    }  ]};

obj.products.forEach((p, i) => {
p.variants.forEach((v) => {
if (v.available) {
var found = v.selectedOptions.find((s) => s.value === 'L');
if (found) {
console.log(`Found a product at index '${i}' with variant ['${v.available}' | '${found.value}']`);
}
}
});
});
.as-console-wrapper { max-height: 100% !important; top: 0; }

关于javascript - 检查 JSON 数据中是否存在多个键值对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49060964/

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