javascriptunderscore.js

How to select properties from an object in Javascript


I have the following object say,

{"id":"kl45wkfj1k4j34", "firstname":"Arun", "lastname":"K"}

and I have the key to be filtered, 'firstname, lastname' assigned in a string using comma separator.

How do I filter that object to get the output as follows:

{"firstname":"Arun", "lastname":"K"}

Solution

  • Underscore's pick method is what you're looking for.

    var obj = { "id": 'kl45wkfj1k4j34', "firstname": "Arun", "lastname": "K" };
    var filter = 'firstname, lastname',
    var result = _.pick(obj, filter.split(', '));