如何使用jQuery或JavaScript

时间:2016-05-23 21:29:39

标签: javascript jquery json

我在JSON之下,面临从JSON数组动态获取密钥和值的困难:

var productJSON = {
    "byProduct": {
        "category": {
            "Entertainment": {
                "TV": 7,
                "Speaker": 24,
                "DVD Player": 5,
                "Home Theater": 4
            },
            "Home": {
                "Sofa Couch": 1,
                "TV Furniture": 4
            },
            "Mobile": {
                "iPhone 5s": 1,
                "Accessories": 4
            }
        }
    }
}

我想要每个类别中的键值,并输入两个不同的数组,一个用于产品名称,另一个用于产品计数,如:

["TV", "Speaker", "DVD Player", "Home Theater","Sofa Couch", "TV Furniture", "iPhone 5s", "Accessories"]

[7, 24, 5, 4,1,4,1,4]

有人可以帮助我如何得到这样的输出?

如何从JSON数组中获取这些值,下面是我的代码,但无法解析每个类别中的所有项目:

var ProductJSON = productJSON.byProduct;
var productsName = [], productCount = [];
Object.keys(ProductJSON.category).forEach(function (v) {
    var k = Object.keys(ProductJSON.category[v])[0];
    productsName.push(k);
    productCount.push(ProductJSON.category[v][k]);
});
console.log(productsName);
console.log(productCount);

提前感谢您的帮助。

2 个答案:

答案 0 :(得分:2)

以下是此fiddle中的完整解决方案。

            var Products = productJSON.byProduct.category;

            var productsName = [], productCount = [];

            for (var product in Products) {
                var items = Products[product]
                for (var item in items) {
                    productsName.push(item);
                    productCount.push(items[item]);
                }
            }
            console.log(productsName);
            console.log(productCount);

这是一般的JavaScript。

答案 1 :(得分:0)

您可以使用lodash forEach执行此类操作:

var productJSON = {"byProduct": {"category": {"Entertainment": {"TV": 7,"Speaker": 24,"DVD Player": 5,"Home Theater": 4},"Home": {"Sofa Couch": 1,"TV Furniture": 4},"Mobile": {"iPhone 5s": 1,"Accessories": 4}}}};

var Products = productJSON.byProduct.category;
var productsName = [],
    productCount = [];

_.forEach(Products, function(items) {
    _.forEach(items, function(v, k) {
        productsName.push(k);
        productCount.push(v);
    });
});

console.log('productsName: ', productsName);
console.log('productCount: ', productCount);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.13.1/lodash.min.js"></script>