Reputation: 1223
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?
Upvotes: 15
Views: 25357
Reputation: 32354
Filter will always return a array to get the first element use pop
return data.filter(subject => subject.id === 1)
.map((subject) => {
return subject.total;
}).pop();
Upvotes: 1
Reputation: 36703
You just need to pick the first element. This should suffice..
return data.filter(subject => subject.id === 1)[0].total+""
Upvotes: 3
Reputation: 26400
What about
return data
.filter(subject => subject.id === 1)
.map(subject => subject.total.toString())[0] // Take the first element of the array :)
Array.map
returns an array. If your initial array contains one element, the output array will also contain one element. Just extract it with [0]
.
Alternatively. find()
returns one object :
return data.find(subject => subject.id === 1).total.toString()
Upvotes: 4
Reputation: 152284
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();
Upvotes: 48