Use the map function to get ids from an array of objects in JavaScript. The below code gets all ids from an array of objects.
array.map(s=>s.id)
Get ids from an array of objects in JavaScript
Simple example code.
<!DOCTYPE html>
<html>
<body>
<script>
var myArray = [{'id':'101','foo':'bar'},
{'id':'201','foo':'bar'}];
var res = myArray.map(s=>s.id);
console.log(res)
</script>
</body>
</html>
Output:
Retrieve user id from an array of object
Find ids for the “Vikram” user.
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: [ “7”, “5” ]
How to convert id’s array of objects to a list JavaScript?
Answer: Use map
If you want to extract values from a collection of objects.
<script>
let list = [
{ id: 1 },
{ id: 2 },
{ id: 3 },
{ id: 4 }
];
let data = list.map((obj) => obj.id);
console.log(data);
</script>
Output: [ 1, 2, 3, 4 ]
Do comment if you have any doubts or suggestions on this JS object topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version