JavaScript: Retrieve a set of properties indicated by the given selectors from an object
JavaScript fundamental (ES6 Syntax): Exercise-49 with Solution
Write a JavaScript program to retrieve a set of properties indicated by the given selectors from an object.
- Use Array.prototype.map() for each selector, String.prototype.replace() to replace square brackets with dots.
- Use String.prototype.split('.') to split each selector.
- Use Array.prototype.filter() to remove empty values and Array.prototype.reduce() to get the value indicated by each selector.
Sample Solution:
JavaScript Code:
//#Source https://bit.ly/2neWfJ2
const get = (from, ...selectors) =>
[...selectors].map(s =>
s
.replace(/\[([^\[\]]*)\]/g, '.$1.')
.split('.')
.filter(t => t !== '')
.reduce((prev, cur) => prev && prev[cur], from)
);
const obj = { selector: { to: { val: 'val to select' } }, target: [1, 2, { a: 'test' }] };
console.log(get(obj, 'selector.to.val', 'target[0]', 'target[2].a'));
Sample Output:
["val to select",1,"test"]
Flowchart:

Live Demo:
See the Pen javascript-basic-exercise-1-49 by w3resource (@w3resource) on CodePen.
Improve this sample solution and post your code through Disqus
Previous: Write a JavaScript program to get an array of function property names from own (and optionally inherited) enumerable properties of an object.
Next: Write a JavaScript program to convert an integer to a suffixed string, adding am or pm based on its value.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends
- Python Interview Questions and Answers: Comprehensive Guide
- Scala Exercises, Practice, Solution
- Kotlin Exercises practice with solution
- MongoDB Exercises, Practice, Solution
- SQL Exercises, Practice, Solution - JOINS
- Java Basic Programming Exercises
- SQL Subqueries
- Adventureworks Database Exercises
- C# Sharp Basic Exercises
- SQL COUNT() with distinct
- JavaScript String Exercises
- JavaScript HTML Form Validation
- Java Collection Exercises
- SQL COUNT() function
- SQL Inner Join