- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 can 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']
- Related Articles
- Retrieve key and values from object in an array JavaScript
- Search by id and remove object from JSON array in JavaScript
- Set object property in an array true/false, whether the id matches with any id from another array of objects in JavaScript?
- Retrieve property value selectively from array of objects in JavaScript
- Can I retrieve multiple documents from MongoDB by id?
- From a list of IDs with empty and non-empty values, retrieve specific ID records in JavaScript
- Program to retrieve the text contents of the user selection using JavaScript.
- Create array from JSON object JavaScript
- Extract the user ID from the username only in MySQL?
- Top n max value from array of object JavaScript
- How to get only the first BOT ID from thes JavaScript array?
- Perform $lookup to array of object id's in MongoDB?
- Building a frequency object from an array JavaScript
- From JSON object to an array in JavaScript
- Retrieve element from local storage in JavaScript?

Advertisements