al. zheic al. zheic - 3 months ago 16
Javascript Question

Customizing objects in Javascript

Please help me with this customization of objects in javascript, I'm a little stuck.

Object

var stocks = [
{
"size": "2",
"count": 5,
"store": {
"id": 3,
"title": "Belconnen"
}
},
{
"size": "3",
"count": 4,
"store": {
"id": 4,
"title": "Canberra"
}
},
{
"size": "4",
"count": 4,
"store": {
"id": 5,
"title": "Bankstown"
}
},
{
"size": "5",
"count": 5,
"store": {
"id": 4,
"title": "Canberra"
}
}];


Expected Output

{3:{"sizes": {2: 3}}},
{4:{"sizes": {3: 3, 5: 3}}},
{5:{"sizes": {4: 3}}}


My code so far

for (var key in stocks) {
var stock = stocks[key];

stores[stock.store.id] = stock.store;
var store = stores[stock.store.id];

if (!store.sizes || !store.sizes.length) {
store.sizes = [stock.size];
}
}


But it keeps overiding the first size value of the store.

Thanks in advance.

Answer

This is one way to solve the problem

    var stocks = [
    {"size": 2, "count": 3, "store": {"id": 3, "name": "Canberra"}}, 
    {"size": 3, "count": 3, "store": {"id": 4, "name": "Belconnen"}},
    {"size": 4, "count": 3, "store": {"id": 5, "name": "Bankstown"}},
    {"size": 5, "count": 3, "store": {"id": 4, "name": "Belconnen"}}];
    
    var obj = {};
    
    stocks.forEach(function(item){
        // initialize if object key not present
        if(!obj[item.store.id]){
           obj[item.store.id] = {"sizes": {}};
        }
        obj[item.store.id]["sizes"][item.size] = item.count;  
    });
    
    console.log(obj);

Here is the working fiddle https://jsfiddle.net/flyinggambit/nc3uny53/

Check the console window for fiddle output