austttn19
austttn19

Reputation: 73

JSON in express.js router with a forEach statement

I'm trying to make my API return a JSON with each of the names of this forEach statement. There are 8 names and it's only possible to res.send once.

code below

timeSeries.forEach(data => {
     res.json(data.metric.labels.instance_name + Math.round(100000 * data.points[0].value.doubleValue) / 1000000 + "%")
})

Upvotes: 1

Views: 95

Answers (2)

Donald Wu
Donald Wu

Reputation: 716

you should return a list result for one json response

const result = timeSeries.map((data, i)=> {
    const name = data.metric.labels.instance_name;
    const roundedValue = Math.round(100000 * data.points[0].value.doubleValue) / 1000000;
    return `${name}: ${roundedValue}%`;
});

res.json({
   result: result
});

Upvotes: 1

Jacob
Jacob

Reputation: 78910

res.json() is used to finalize a response by serialize the given data as JSON, send it as the response body, then end the response. Therefore, calling it more than once doesn't make sense.

I think what you're wanting to do is map timeSeries data into an array of values and send the JSON of that computed array of data:

res.json(
  timeSeries.map(data => {
    const roundedValue = Math.round(100000 * data.points[0].value.doubleValue) / 1000000;
    return `${data.metric.labels.instance_name}${roundedValue}%`;
  })
)

Upvotes: 1

Related Questions