Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Retrieve user id from array of object - JavaScript
Suppose, we have an array of objects where the user names are mapped to some unique ids like this ?
const arr = [
{"4": "Rahul"},
{"7": "Vikram"},
{"6": "Rahul"},
{"3": "Aakash"},
{"5": "Vikram"}
];
As apparent in the array, same names can have more than one ids but same ids cannot be used to map two different names.
We are required to write a JavaScript function that takes in one such array as the first argument and a name string as the second argument. The function should return an array of all ids that were used to map the name provided as second argument.
Example
Following is the code ?
const arr = [
{"4": "Rahul"},
{"7": "Vikram"},
{"6": "Rahul"},
{"3": "Aakash"},
{"5": "Vikram"}
];
const name = 'Vikram';
const findUserId = (arr, name) => {
const res = [];
for(let i = 0; i < arr.length; i++){
const key = Object.keys(arr[i])[0];
if(arr[i][key] !== name){
continue;
};
res.push(key);
};
return res;
};
console.log(findUserId(arr, name));
Output
This will produce the following output in console ?
['7', '5']
Alternative Method Using filter() and map()
Here's a more concise approach using array methods:
const arr = [
{"4": "Rahul"},
{"7": "Vikram"},
{"6": "Rahul"},
{"3": "Aakash"},
{"5": "Vikram"}
];
const findUserIdAlt = (arr, name) => {
return arr
.filter(obj => Object.values(obj)[0] === name)
.map(obj => Object.keys(obj)[0]);
};
console.log(findUserIdAlt(arr, 'Rahul'));
console.log(findUserIdAlt(arr, 'Aakash'));
['4', '6'] ['3']
Method Using Object.entries()
Another approach using Object.entries() for better readability:
const arr = [
{"4": "Rahul"},
{"7": "Vikram"},
{"6": "Rahul"},
{"3": "Aakash"},
{"5": "Vikram"}
];
const findUserIdEntries = (arr, name) => {
const result = [];
arr.forEach(obj => {
const [id, userName] = Object.entries(obj)[0];
if (userName === name) {
result.push(id);
}
});
return result;
};
console.log(findUserIdEntries(arr, 'Rahul'));
['4', '6']
Comparison of Methods
| Method | Readability | Performance | Best For |
|---|---|---|---|
| For loop with Object.keys() | Good | Fastest | Large datasets |
| filter() and map() | Excellent | Moderate | Functional programming style |
| forEach() with Object.entries() | Very Good | Good | Clear key-value handling |
Conclusion
All three methods effectively retrieve user IDs from an array of objects. Choose the for loop for performance-critical applications, or use the filter/map approach for cleaner, more functional code.
