I would like to produce an array (plus, separately, an object, if possible) from the unique ‘custRef’ values in the following array:
[
{
"id": 1233,
"custRef": "ABC1234",
"somethingElse": 10.0,
"someRef": "37856394943222"
},
{
"id": 1234,
"custRef": "ABC1235",
"somethingElse": 11.0,
"someRef": "37856394943222"
},
{
"id": 1235,
"custRef": "ABC1235",
"somethingElse": 13.0,
"someRef": "3498537945734567"
}
]
Preferred results:
I would like to produce this array:
[
{
"custRef": "ABC1234",
"items": [
{
"id": 1233,
"custRef": "ABC1234",
"somethingElse": 10.0,
"someRef": "37856394943222"
}
]
},
{
"custRef": "ABC1235",
"items": [
{
"id": 1234,
"custRef": "ABC1235",
"somethingElse": 11.0,
"someRef": "37856394943222"
},
{
"id": 1235,
"custRef": "ABC1235",
"somethingElse": 13.0,
"someRef": "3498537945734567"
}
]
}
]
… and additionally, if possible, this object:
{
"ABC1234": [
{
"id": 1233,
"custRef": "ABC1234",
"somethingElse": 10.0,
"someRef": "37856394943222"
}
],
"ABC1235": [
{
"id": 1234,
"custRef": "ABC1235",
"somethingElse": 11.0,
"someRef": "37856394943222"
},
{
"id": 1235,
"custRef": "ABC1235",
"somethingElse": 13.0,
"someRef": "3498537945734567"
}
]
}
I assume that this would be some kind of combination of .filter() and .map (or maybe .reduce()) but I don’t really know what I’m doing, and so don’t really know what I am supposed to be looking for.
Assuming that I plop the above source array into a variable named ‘orderItems‘ I have managed to produce a simple array of the unique ‘custRef‘ values, with the below javascript. However, I’m failing to find a way use that effectively … or knowing if I should be using it at all?
var uniqueOrdersWtItms = Object.keys(orderItems.reduce((r,{oh_cust_order_ref}) => (r[oh_cust_order_ref]='', r) , {}));
Like I say, I can’t stress this enough, I don’t really know what I need to look for, so whilst I have tried to build this through any number of search results both here and elsewhere … it’s hard to know what to ask for. If anyone can help, that’d be amazing.
stackoverflow’s suggestion gave this answer:
Creating new array with unique key while mapping through given array
But it doesn’t seem to do what I want, or I cannot understand it well enough. 🙁