如何在javascript中使用特定的键和值循环遍历json对象?

时间:2018-09-11 02:03:15

标签: javascript php jquery wordpress woocommerce

我正在遍历具有以下结构的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”属性(非零数量)

2 个答案:

答案 0 :(得分:3)

您可以先filter数组:

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
        }
    ]
};
console.log(
  my_products.products.filter(({ stock_quantity, in_stock }) => (
    in_stock && stock_quantity === 1
  ))
);

答案 1 :(得分: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>