anonn023432 anonn023432 - 1 month ago 9
React JSX Question

React extract value from list-keys

getEmployeeCredits(id) {
if (this.state.company_roles) {
return this.state.company_roles.map(function (cr, i) {
if (cr.id === id) {
return cr.assigned_credits
}
}.bind(this));
}
}


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
undefined
values and then just use the value
10000.0
but is there a more elegant way to do this?

EDIT: THE
if (cr.id === 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 => crItem.id === 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.