I'm trying to loop through the following :
{
"machine": [{
"cost_center": "15023 DC1 M3 - Hassia1",
"item": [{
"batchno": "367721",
"itemno": "12028"
}, {
"batchno": "367722",
"itemno": "12328"
}, {
"batchno": "367723",
"itemno": "12608"
}]
}, {
"cost_center": "15033 DC1 M4 - Hamba",
"item": [{
"batchno": "367729",
"itemno": "11850"
}, {
"batchno": "367730",
"itemno": "11851"
}, {
"batchno": "367731",
"itemno": "11852"
}]
}, {
"cost_center": "15043 DC1 M5 - 1KG Machine",
"item": {
"batchno": "367732",
"itemno": "12592"
}
}]
}
var json = '{"machine":[{"cost_center":"15023 DC1 M3 - Hassia1","item":[{"batchno":"367721","itemno":"12028"},{"batchno":"367722","itemno":"12328"},{"batchno":"367723","itemno":"12608"}]},{"cost_center":"15033 DC1 M4 - Hamba","item":[{"batchno":"367729","itemno":"11850"},{"batchno":"367730","itemno":"11851"},{"batchno":"367731","itemno":"11852"}]},{"cost_center":"15043 DC1 M5 - 1KG Machine","item":{"batchno":"367732","itemno":"12592"}}]}';
var obj = JSON.parse(json);
var db = obj.machine;
for (var m in db) {
if (db.hasOwnProperty(m)) {
var item = db[m].item;
console.log('cost_center ' + m + ' = ' + db[m].cost_center);
for (var i in item) {
if (item.hasOwnProperty(i)) {
var prod = item[i];
console.log('-itemno ' + i + ' ' + prod.itemno);
}
}
}
}
I have found similar question here but the difference lay on my data, my first 2 cost_centers have arrays as elements, my the 3rd one isn't an array.
cost_center 0 = 15023 DC1 M3 - Hassia1
-itemno 0 12028
-itemno 1 12328
-itemno 2 12608
cost_center 1 = 15033 DC1 M4 - Hamba
-itemno 0 11850
-itemno 1 11851
-itemno 2 11852
cost_center 2 = 15043 DC1 M5 - 1KG Machine
-itemno batchno undefined
-itemno itemno undefined
How can I loop through everything and still get all the values from the cost_center which doesn't contain an array ? Thanks