I have an array in the below format.
var produce = [
{'supplierID':1,'produceID':1, 'name':'apple', 'qty': 10},
{'supplierID':1,'produceID':2, 'name':'carrot', 'qty': 10},
{'supplierID':1,'produceID':2, 'name':'bean', 'qty': 20},
{'supplierID':1,'produceID':1, 'name':'bananna', 'qty': 30},
{'supplierID':1,'produceID':1, 'name':'orange', 'qty': 65},
{'supplierID':2,'produceID':2, 'name':'pumpkin', 'qty': 120},
{'supplierID':2,'produceID':2, 'name':'cucumber', 'qty': 18},
{'supplierID':2,'produceID':1, 'name':'strawberry', 'qty': 130},
{'supplierID':2,'produceID':1, 'name':'mango', 'qty': 60},
{'supplierID':2,'produceID':1, 'name':'grapes', 'qty': 140}
];
//produceID 1 = fruit
//produceID 2 = veg
I want it in this sort of format.
{
'id': 1,
'fruit': [
{
'name': 'apple',
'qty': 10
},
{
'name': 'bananna',
'qty': 30
},
{
'name': 'orange',
'qty': 65
}
],
'veg': [
{
'name': 'carrot',
'qty': 10
},
{
'name': 'bean',
'qty': 20
},
]
},
{
'id': 2,
'fruit': [
{
'name': 'strawberry',
'qty': 130
},
{
'name': 'mango',
'qty': 60
},
{
'name': 'grapes',
'qty': 140
}
],
'veg': [
{
'name': 'pumpkin',
'qty': 120
},
{
'name': 'cucumber',
'qty': 18
},
]
}
So that I can group my items first by supplier then by produce type (fruit/veg) (using angular js)
<div style="width:100%" ng-repeat="res in results">
<h2>Supplier - {{res.id}}</h2>
<h3>Fruit</h3>
<ul>
<li ng-repeat="f in res.fruit">{{f.name}}</li>
</ul>
<h3>Veg</h3>
<ul>
<li ng-repeat="v in res.veg">{{v.name}}</li>
</ul>
</div>
A working eg of this can be seen in this codepen. http://codepen.io/anon/pen/rVVJjg
How can I achieve this?
So far I have found that I need to find all suppliers which I can with the below.
//get unique suppliers
var unique = {};
var distinct = [];
for( var i in produce ){
if( typeof(unique[produce[i].supplierID]) == "undefined"){
distinct.push(produce[i].supplierID);
}
unique[produce[i].supplierID] = 0;
}
console.log(distinct);
I can also get the right format for supplierID == 1 as shown below, but not sure how I could scale this to handle multiple suppliers
var fruit = [];
var veg = [];
var res = [];
for (var i in produce) {
if (produce[i].supplierID == 1) {
if (produce[i].produceID == 1) {
fruit.push(produce[i]);
}
else {
veg.push(produce[i]);
}
}
}
res.push(fruit);
res.push(veg);
console.log(res);
How can I acheive this?
sort: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…