0

I have written the following code to return an object transformedRes having 4 values: Id, name, message, status In case of status, I am getting an audits array with almost 100 elements. However, I need to fetch only the last element from audit and then the audit.msg from the last audit element

const transformedRes = {
  Id: res.data.map(host => host._id),
  name: res.data.map(host => host._val.hostName),
  message: res.data.map(host => host._val.message),
  status: res.data.map(host => {
    if (host) {
      const auditsMsg = host._val.audits.map(audit =>  audit.msg);
    }
  })
};
R. Richards
  • 23,283
  • 10
  • 63
  • 62
meallhour
  • 11,517
  • 14
  • 47
  • 86

1 Answers1

0

Why do you use map, if you just want the last element?

const transformedRes = {
  Id: res.data.map(host => host._id),
  name: res.data.map(host => host._val.hostName),
  message: res.data.map(host => host._val.message),
  status: res.data.map(host => {
    return host._val.audits[host._val.audits.length-1].msg; //Last element of audits array
  }
};

More about fetching the last element of an array is described in this stack post: Selecting last element in JavaScript array

Screeper
  • 148
  • 9