1

I've below JSON, am facing difficulty to get the key and value dynamically from JSON array:

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

I'm want key, value from each category and put in two different array, one for product name and another for product count like:

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

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

Can someone help how can I get the output like this?

How can I get these value from above JSON array, below is my code but not able to parse all the item from each category:

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

Thanks for your help in advance.

java begineer
  • 319
  • 5
  • 15

2 Answers2

2

Here is the complete solution in this 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);

This is in plain JavaScript.

pparas
  • 549
  • 4
  • 13
0

You can do something like this using 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>
Yosvel Quintero
  • 18,669
  • 5
  • 37
  • 46