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 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 linux驱动,linux应用,多线程