In JavaScript, we can find and print an object from an array by matching its id property. This is commonly done using methods such as filter(), find(), Underscore.js _.find(), and the Map data structure.
- Searches for an object using its
idproperty. - Retrieves the matching object or a specific property from it.
- Provides multiple approaches depending on the use case.
Approach 1: Using Array.filter()
The filter() method creates a new array containing all objects that satisfy the specified condition. Since it returns an array, the first matching object can be accessed using [0].
Example: Finds and prints the object whose id is 2.
//Driver Code Starts
const a = [
{ id: 1, name: "a" },
{ id: 2, name: "Dua" },
{ id: 3, name: "c" }
];
const id = 2;
//Driver Code Ends
const result = a.filter(obj => obj.id === id);
//Driver Code Starts
console.log(result[0]);
//Driver Code Ends
Output
{ id: 2, name: 'Dua' }
Note: filter() returns an array even when only one object matches. Use [0] to access the first matching object.
Approach 2: Using find()
The find() method returns the first object that satisfies the specified condition. It is more suitable than filter() when only one matching object is required.
Example: Finds the object with the specified id and prints its name property.
const a = [
{ id: 1, name: "a" },
{ id: 2, name: "b" },
{ id: 3, name: "c" }
];
const id = 2;
const prop = "name";
const result = a.find(item => item.id === id);
if (result) {
console.log(result[prop]);
}
Output
b
Note: find() returns the first matching object or undefined if no object matches the given id.
Approach 3: Using Underscore.js _.find()
Underscore.js provides the _.find() function to search for the first element that satisfies a condition. It can also accept an object to match specific properties.
Example: Uses _.find() to find an object by its id and print its name property.
const _ = require('underscore');
const a = [
{ id: 1, name: "a" },
{ id: 2, name: "b" },
{ id: 3, name: "c" }
];
const id = 2;
const prop = "name";
const obj = _.find(a, { id: id });
console.log(obj?.[prop]);
Output
bNote: obj?.[prop] uses optional chaining to safely access the specified property when a matching object is found.
Approach 4: Using Map Data Structure
The Map data structure can store objects using their id as keys. This allows objects to be retrieved directly using their IDs.
Example: Stores objects in a Map and retrieves the object with the required id.
const a = [
{ id: 1, name: "a" },
{ id: 2, name: "b" },
{ id: 3, name: "c" }
];
const map = new Map();
a.forEach(obj => map.set(obj.id, obj));
const reqId = 2;
const reqObj = map.get(reqId);
const reqProp = "name";
console.log(reqObj?.[reqProp]);
Output
b
Note: Map is useful when objects need to be looked up by ID repeatedly, as each object can be retrieved directly using its ID.