如果在JSON对象中找到密钥,则仅触发一次

时间:2018-11-21 18:00:27

标签: javascript json each

我有一个产品的JSON对象。在对象中,我要检查是否有任何产品的featured键设置为true。如果该键在对象内的任何位置存在,我想一次在结果上方添加一个h3

假设我有一个包含4个产品的对象,并且其中一个产品的featured键设置为true,我将如何调整此代码,以使h3仅被添加一次(当前是被全部添加4次)?

var searchResult = '';
$.each(products, function (id, product) {
    if (products[id].featured) { searchResult += '<h3>Featured</h3>'; }
});

2 个答案:

答案 0 :(得分:7)

return false回调中添加$.each,以打破循环

var searchResult = '';
$.each(products, function (id, product) {
    if (products[id].featured) { 
        searchResult += '<h3>Featured</h3>'; 
        return false;
    }       
});

您可以改用Array#find()Array#some()来缩短此时间

var searchResult = '';
var featured =  products.some(function(prod){ return prod.featured});
if(featured){
   searchResult += '<h3>Featured</h3>'; 
}

答案 1 :(得分:1)

只有一个变量可以为您保持featured状态,并在匹配时在循环中对其进行修改

var searchResult = '';
var featured = false;
$.each(products, function (id, product) {
    if (products[id].featured) { featured = true; }
});

if(featured === true){
    searchResult += '<h3>Featured</h3>';
}