我正在遍历具有以下结构的json对象:

var my_products = {
    "products": [
        {
            "title": "Product 1",
            "id": 001,
            "stock_quantity": 0,
            "in_stock": false
        },
        {
            "title": "Product 2",
            "id": 002,
            "stock_quantity": 0,
            "in_stock": false
        },
        {
            "title": "Product 3",
            "id": 003,
            "stock_quantity": 1,
            "in_stock": true
        },
        {
            "title": "Product 4",
            "id": 004,
            "stock_quantity": 1,
            "in_stock": true
        }
    ]
};


我可以使用以下代码遍历对象:

for(var i=0; i<my_products.products.length; i++) {
    var product = my_products.products[i];
    console.log(product);
    console.log('in_stock:',product.in_stock);
}


您知道如何遍历每条具有"stock_quantity": 1 and "in_stock": true属性的产品的记录吗?

在上面的示例中,有2个产品记录具有“ stock_quantity": 1属性(非零数量)

最佳答案

只需使用filter条件即可迭代和if数据。



var my_products = {
    "products": [
        {
            "title": "Product 1",
            "id": 001,
            "stock_quantity": 0,
            "in_stock": false
        },
        {
            "title": "Product 2",
            "id": 002,
            "stock_quantity": 0,
            "in_stock": false
        },
        {
            "title": "Product 3",
            "id": 003,
            "stock_quantity": 1,
            "in_stock": true
        },
        {
            "title": "Product 4",
            "id": 004,
            "stock_quantity": 1,
            "in_stock": true
        }
    ]
};
var filterData = [];
$.each(my_products.products, function(){
    if (this.in_stock && this.stock_quantity === 1) {
        filterData.push(this);
    }
});
console.log(filterData);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

07-28 02:49
查看更多