Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning a single value from a filter

I am trying to return a single value from a filter that returns a large object.

return data.filter(subject => subject.id === 1)
   .map((subject) => {
   return subject.total.toString();
    });

I have tried, toString, JSON.parse and a few more but always get it either as a single array value.

[112]

or a string inside the array

["112"]

but not a single returned value

112

Is map the wrong method? How do I return a pure integer or string would do?

like image 387
leblaireau Avatar asked Nov 29 '22 13:11

leblaireau


2 Answers

Instead of filter which returns an array with filtered values, use find:

const subject = data.find(subject => subject.id === 1);
return subject.total.toString();

or shorter:

return data.find(subject => subject.id === 1).total.toString();
like image 124
hsz Avatar answered Dec 04 '22 02:12

hsz


You just need to pick the first element. This should suffice..

return data.filter(subject => subject.id === 1)[0].total+""
like image 43
void Avatar answered Dec 04 '22 03:12

void