简体   繁体   中英

How to loop through json object with specific key and value in javascript?

I am looping through a json object with the structure below:

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
        }
    ]
};

I can loop through the object with the code below:

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);
}

Do you know how can I loop through each record where Products that have a "stock_quantity": 1 and "in_stock": true properties?

In the example above there are 2 product records that have a " stock_quantity": 1 property(not zero quantity)

You can filter the array first:

 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 )) ); 

Simply you can iterate and filter data with if condition.

 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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM