You can use the find()
method in JavaScript to get the row of an array of objects containing a given field/value. Here's how you can do it:
let array = [
{ id: 1, name: 'John' },
{ id: 2, name: 'Jane' },
{ id: 3, name: 'Doe' }
];
let foundObject = array.find(function(item) {
return item.id === 2; // replace 2 with the value you're looking for
});
console.log(foundObject); // Output: { id: 2, name: 'Jane' }
In this example, find()
iterates through each object in the array and returns the first one that matches the provided condition (in this case, id === 2
). If no objects match, it returns undefined
.
If you want to use ES6 arrow function, you can simplify it like this:
let foundObject = array.find(item => item.id === 2);