To find an object within an array of objects in JavaScript, you can use the find
method. The find
method returns the value of the first element in the array that satisfies the given function conditions.
JavaScript find in array of objects example
Simple example code used find
to search for an object within an array of objects:
<!DOCTYPE html>
<html>
<body>
<script>
const people = [
{ name: 'John', age: 25 },
{ name: 'Mary', age: 30 },
{ name: 'Jane', age: 28 }
];
// Find the object with name 'Mary'
const result = people.find(person => person.name === 'Mary');
console.log(result);
</script>
</body>
</html>
Output:
Replacing the array element
To replace an element in an array in JavaScript, you can use the array index notation to access the element you want to replace and assign a new value to it.
const myArray = ['apple', 'banana', 'orange'];
console.log(myArray); // ['apple', 'banana', 'orange']
// Replace the second element with 'pear'
myArray[1] = 'pear';
console.log(myArray); // ['apple', 'pear', 'orange']
Find an object within an array of objects, and replace a property of that object:
const people = [
{ name: 'John', age: 25 },
{ name: 'Mary', age: 30 },
{ name: 'Jane', age: 28 }
];
// Find the object with name 'Mary' and update her age
const personToUpdate = people.find(person => person.name === 'Mary');
if (personToUpdate) {
personToUpdate.age = 35;
console.log('Updated Mary\'s age:', personToUpdate);
} else {
console.log('Person not found');
}
console.log('All people:', people);
Comment if you have any doubts or suggestions on this JS array object topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version