find value for a key in an array in javascript

To find the value for a specific key in an array that contains objects in JavaScript, you can use the find() method followed by the bracket notation to access the value.

Example array with objects:

index.tsx
let array = [
    {id: 1, name: 'Alice'},
    {id: 2, name: 'Bob'},
    {id: 3, name: 'Charlie'}
];
100 chars
6 lines

To find the value for the key name for the object with id equal to 2, you can use the following code:

index.tsx
let foundObject = array.find(obj => obj.id === 2);
let value = foundObject['name'];
console.log(value); // outputs 'Bob'
121 chars
4 lines

Alternatively, you can also use dot notation to access the value:

index.tsx
let value = foundObject.name;
console.log(value); // outputs 'Bob'
67 chars
3 lines

gistlibby LogSnag