I’m working on a chart with the following array of objects.
var probeData = [ { min: 0.02, max: 1.44, avg: 0.73 },
{ min: 0.06, max: 1.57, avg: 0.76 } ]
And the callback below.
generateLabels: (_chart) => {
return probeData.map((obj, i) => ({
text: `UCL ${i+1} ${obj.max}`,
index: i,
})
);
Now, instead of returning only the max
, I need to return, for each object also min
and avg
.
I tried the following solution but the callback returns only the two avg
instead of the 6 values.
generateLabels: (_chart) => {
return probeData.map((obj, i) => ({
text: `UCL ${i+1} ${obj.max}`,
index: i,
},
{
text: `LCL ${i+1} ${obj.min}`,
index: i,
},
{
text: `AVG ${i+1} ${obj.avg}`,
index: i,
})
);
2
Answers
you are probably looking for
flatMap
You are accidentally using the comma operator, but want to map one item to multiple objects. Try
Array.flatMap()
, as cmgchess shows.The comma operator is a comma-separated list of expressions which evaluates to its last expression. In your case, the previous object initializations are therefore unused.
To return multiple objects in JavaScript, try returning them as part of another object (e.g. an array).
It seems you’d want to afterwards flatten the resulting array of arrays. Instead of calling
Array.map()
followed byArray.flat()
, JS providesArray.flatMap()
for convenience.