How to print object by id in an array of objects in JavaScript ?
Last Updated :
03 Jan, 2024
In this article, we will learn how to print object by id in an array of objects in JavaScript. We have an array of objects and in every object, there is a key named id, whose value is a number. We have to return the object which matches the specified condition.
There are many approaches to printing objects by id in an array of objects in JavaScript:
This method is used for creating a new array from an existing array after applying some conditions.
Example: In this example, we are using Array.filter() Method.
Javascript
let data = [
{ id: 1, name: "a" },
{ id: 2, name: "b" },
{ id: 3, name: "c" },
{ id: 4, name: "d" },
{ id: 5, name: "e" },
{ id: 6, name: "f" },
];
let idYouWant = 1;
let propertyYouWant = "name" ;
let res = data.filter((item) => {
return item.id == idYouWant;
});
let exactRes = res[0][propertyYouWant];
console.log(exactRes);
|
First, we are searching in which object the given id exists, then we extract the name property from that object.
Example: In this example, we are using Array.find() Method.
Javascript
let data = [
{ id: 1, name: "a" },
{ id: 2, name: "b" },
{ id: 3, name: "c" },
{ id: 4, name: "d" },
{ id: 5, name: "e" },
{ id: 6, name: "f" },
];
let idYouWant = 2;
let propertyYouWant = "name" ;
let res = data.find((item) => {
return item.id == idYouWant;
});
console.log(res[propertyYouWant]);
|
Using for loop first we are iterating the array and searching in which object the given id is present and after that, we are printing the property we wanted.
Example: In this example, we are using for loop.
Javascript
let data = [
{ id: 1, name: "a" },
{ id: 2, name: "b" },
{ id: 3, name: "c" },
{ id: 4, name: "d" },
{ id: 5, name: "e" },
{ id: 6, name: "f" },
];
let idYouWant = 2;
let propertyYouWant = "name" ;
for (let i = 0; i < data.length; i++) {
if (data[i].id == idYouWant) {
console.log(data[i][propertyYouWant]);
}
}
|
The _.find() function looks at each element of the list and returns the first occurrence of the element that satisfy the condition. If any element of the list is not satisfy the condition then it returns the undefined
value.
Example: In this example, we are using Underscore.js _.find() Function.
Javascript
const _ = require( 'underscore' );
let data = [
{ id: 1, name: "a" },
{ id: 2, name: "b" },
{ id: 3, name: "c" },
{ id: 4, name: "d" },
{ id: 5, name: "e" },
{ id: 6, name: "f" },
];
let idYouWant = 2;
let propertyYouWant = "name" ;
let obj = _.find(data, function (obj) {
return obj.id == idYouWant })
console.log(obj[propertyYouWant]);
|
Output:
b
Share your thoughts in the comments
Please Login to comment...