I have the following
const measures = [
{ "13798494-value": 0.207, readingDate: "26/06/2023" },
{ "4958469-value": 0.211 , readingDate: "26/06/2023" },
{ "13798494-value": 0.214 , readingDate: "27/06/2023" },
{ "4958469-value": 0.123, readingDate: "27/06/2023" }
]
but I need it like this
const measures = [
{ readingDate: "26/06/2023", "13798494-value": 0.207, "4958469-value": 0.211 },
{ readingDate: "27/06/2023", "13798494-value": 0.214, "4958469-value": 0.123 }
]
I’ve tried the following but I cant get it to work
const reduceThis = measures?.reduce(
(acc, item) => {
const key = Object.keys(item)[0]
const value = Object.values(item)[0]
const queryResult = acc.find(
(qr) => qr?.readingDate === item?.readingDate,
)
if (queryResult) {
queryResult.results.push({ [key]: value })
} else {
let newQR = {
readingDate: item?.readingDate,
results: [{ [key]: value }],
}
acc.push(newQR)
}
return acc
},
[],
)
But this comes back as
const measures = [
{ readingDate: "26/06/2023", results: [{"13798494-value": 0.207, "4958469-value": 0.211}] },
{ readingDate: "27/06/2023", results: [{"13798494-value": 0.214, "4958469-value": 0.123}] }
]
So I’m nearly there but cant quite get it.
The format "XXXXXXXX-value" is dynamic and the XXXXXXXX can be anything so we cant directly reference those values.
Thanks
4
Answers
Try this
Start reduce with an empty object
{}
. GetreadingDate
from current index and check if it already exists in the object. If yes, add the remaining values...rest
from the measures object for the date. If not, add the date as a new key and assign remaining values then. Convert to an array afterwards.To make it fast use
Array::reduce
to collect items with the same readingDate in an array and in a map (for further quick access to add additional properties):You can reduce the array of object to build a new one item by item. As you iterate, if the current object does not exist in the new one, you add it, otherwise, you spread the contents of the current object into the existing one.
this might be consolidated but is in my opinion easier to read