JavaScript Get Value by Key in Array of Objects
If you want to get the values of an array of objects using its keys, you need to understand array of object concepts. So, in this article, we’ve explored how to get value by key in an array of objects in javascript.
Understanding Arrays of Objects
An array of objects is a collection where each element represents an individual object. Each object contains multiple properties, or keys, each associated with a specific value. This structure enables developers to organize and store data efficiently.
const books = [
{ title: "The Great Gatsby", author: "F. Scott Fitzgerald", year: 1925 },
{ title: "To Kill a Mockingbird", author: "Harper Lee", year: 1960 },
// Additional book objects
];
To access specific information, such as the title or author of a book, we need to employ the “Get Value by Key” operation.
Getting Values by Key:
1. Using forEach method
This is one of the higher-order functions in javascript. The forEach method iterates through the array and allows us to access the value using the key directly
Here’s an example to get value by key using forEach
() method:
function getValueByKey(booksArray, key) {
let result;
booksArray.forEach((book) => {
if (key in book) {
result = book[key];
}
});
return result;
}
const bookTitle = getValueByKey(books, "title");
console.log(bookTitle); // Output: "The Great Gatsby"
2. Using the map method:
The map method creates a new array by applying a function to each element. We can use it to create an array of specific values based on the provided key:
function getValuesByKey(booksArray, key) {
return booksArray.map((book) => book[key]);
}
const bookAuthors = getValuesByKey(books, "author");
console.log(bookAuthors); // Output: ["F. Scott Fitzgerald", "Harper Lee"]
3. Using the find method:
The find method allows us to locate the first element in the array that satisfies a given condition:
function getBookByAuthor(booksArray, authorName) {
return booksArray.find((book) => book.author === authorName);
}
const bookByAuthor = getBookByAuthor(books, "Harper Lee");
console.log(bookByAuthor); // Output: { title: "To Kill a Mockingbird", author: "Harper Lee", year: 1960 }
Conclusion
So, In this article, we learned 3 methods to get value by key in array of object in javascript by using built-in array methods like forEach, map, and find. Armed with these techniques, you can confidently navigate and extract specific information from arrays of objects, making your JavaScript programming experience even more rewarding. Happy coding!