在JSON中找到最小的子项

时间:2016-02-21 10:20:59

标签: javascript html json

考虑像这样的JSON

{
    "products": {
        "c1": {
            "stock": 100
        },
        "c2": {
            "stock": 200
        },
        "c3": {
            "stock": 300
        },
        "c4": {
            "stock": 400
        },
        "c5": {
            "stock": 500
        }
    }
}

为了找到最少的股票,我写了这样的代码

 var minStock=Math.min(
      products.c1.stock,
      products.c2.stock,
      products.c3.stock,
      products.c4.stock,
      products.c5.stock
      )
  console.log(minStock);

现在我想知道基于股票价值的c1,c2,c3,c4或c5是最小的,在这种情况下说

console.log("c1 is minimum with stock 100");

3 个答案:

答案 0 :(得分:5)

这是Array#reduce()的解决方案。它也返回相同的引用:



JLabel Uniqlbl = new JLabel(NHome.hhhhh);




答案 1 :(得分:2)

使用Object.keysarray#reduce进行快速简便的解决方案

var min = Object.keys(products).reduce(function(min, item) {
    return products[item].stock < products[min].stock ? item : min;
});
console.log(min, 'is minimum with stock', products[min].stock);

Object.keysarray#maparray#sort

var min = Object.keys(products).map(function(item) {
    return {product: item, stock: products[item].stock}
}).sort(function(a, b) {
    return a.stock - b.stock;
})[0]
console.log(min.product, 'is minimum with stock', min.stock);

答案 2 :(得分:1)

具有Array.sort功能的替代方案:

var obj = {
        "products": {            
            "c2": {
                "stock": 200
            },
            "c3": {
                "stock": 300
            },
            "c4": {
                "stock": 400
            },
            "c5": {
                "stock": 500
            },
            "c1": {
                "stock": 100
            },
        }
    };

    var products = Object.keys(obj.products);
    products.sort(function(a,b){
        return obj.products[a].stock - obj.products[b].stock;
    });
    console.log(products[0] + " is minimum with stock " + obj.products[products[0]].stock);
    // c1 is minimum with stock 100

https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Global_Objects/Array/sort