Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get value in an object array by key

how can I get value in an object array by a key, which is also in this object array.

the object array looks like this:

const objectArray = [
    {key: "1", value: "12321"},
    {key: "2", value: "asdfas"}
]

I have now the value of key, e.g. key = 1, but I want to get 12321 as result.

any solution?

like image 837
user1938143 Avatar asked Sep 20 '25 12:09

user1938143


1 Answers

You can use .find() to achieve it.

Try this:

Working Demo

this.objectArray.find(x => x.key == "1").value

To handle exception, if the item doesn't exists in the array, do this:

let item = this.objectArray.find(x => x.key == "1")
this.value = item ? item.value : null
like image 178
Adrita Sharma Avatar answered Sep 23 '25 02:09

Adrita Sharma