anonn023432 anonn023432 - 1 month ago 9
React JSX Question

React extract value from list-keys

getEmployeeCredits(id) {
if (this.state.company_roles) {
return (cr, i) {
if ( === id) {
return cr.assigned_credits

I want to return the assigned credits of the company role whose value matches over here. But the value which is returned is:
[undefined, undefined, undefined, "10000.0"]

In this the undefined value is because of company roles for which the values didn't match. I can delete all the
values and then just use the value
but is there a more elegant way to do this?

if ( === id)
condition will always be true for only a single value.

Answer Source

If you want to look-up an array for a single value, use Array.prototytype.find.

Adjusted to your example:

const foundCompanyRoleItem = this.state.company_roles.find(crItem => === id); return foundCompanyRoleItem.assigned_credits;

This will always return a matching value instead of an array as in the case of .filter.

P.S.: I suggest to use ES6 syntax for your project as well. In the above example, you can see the benefit as my example uses an arrow function introduced in ES6. It makes expressions cleaner and more reasonable.