w3resource

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:

flowchart: Retrieve a set of properties indicated by the given selectors from an object

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.



JavaScript: Tips of the Day

Returns an array of n-tuples of consecutive elements

Example:

const tips_arr = (n, arr) =>  n > arr.length ? [] : arr.slice(n - 1).map((v, i) =>[...arr.slice(i, i + n - 1), v]);
console.log(tips_arr(2, [1, 2, 3, 4, 5])); 
console.log(tips_arr(3, [1, 2, 3, 4, 5]));
console.log(tips_arr(5, [1, 2, 3, 4]));

Output:

[[1, 2], [2, 3], [3, 4], [4, 5]]
[[1, 2, 3], [2, 3, 4], [3, 4, 5]]
[]