
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- 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 Property Value Selectively from Array of Objects in JavaScript
Suppose, we have an array of objects like this −
const arr = [ { id : "23", name : "Item 1", isActive : true}, { id : "25", name : "Item 2", isActive : false}, { id : "26", name : "Item 3", isActive : false}, { id : "30", name : "Item 4", isActive : true}, { id : "45", name : "Item 5", isActive : true} ];
We are required to write a JavaScript function that takes in one such object and return an array of the value of "id" property of all those objects that have true value for the "isActive" property.
Example
The code for this will be −
const arr = [ { id : "23", name : "Item 1", isActive : true}, { id : "25", name : "Item 2", isActive : false}, { id : "26", name : "Item 3", isActive : false}, { id : "30", name : "Item 4", isActive : true}, { id : "45", name : "Item 5", isActive : true} ]; const findActive = (arr = []) => { const res = []; for(let i = 0; i < arr.length; i++){ const obj = arr[i]; const { id, isActive } = obj; if(isActive){ res.push(id); } }; return res; }; console.log(findActive(arr));
Output
And the output in the console will be −
[ '23', '30', '45' ]
Advertisements