dongliang2005 2018-09-11 02:03
浏览 52
已采纳

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

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)

  • 写回答

2条回答 默认 最新

  • douhao5280 2018-09-11 02:35
    关注

    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>

    </div>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?