I have an array of objects
const array = [
{a: 1, b:4},
{a: 2, b:5},
{a: 3, b:6},
]
And i need to find one element in array and recieve only a certain value of object's property. But how can i do it with filter. I tried to do it this way This one didn't work
const b_Value = array.filter(element => element.a === 3).b
Is it possible do get value in filter, not element itself? Also i tried to use if and return but it didnt work also
CodePudding user response:
.filter()
returns an array, not a single element. You could index that array:
const b_Value = array.filter(element => element.a === 3)[0].b;
Or perhaps use .find()
:
const b_Value = array.find(element => element.a === 3).b;
Of course, in either case you'll want to define how you should handle it if (1) no results match or (2) multiple results match.
For example, you might use optional chaining for the possibility of no matching results:
const b_Value = array.find(element => element.a === 3)?.b;
In which case b_Value
could be null
.