Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"}
like image 267
Arun Selva Kumar Avatar asked Dec 19 '22 19:12

Arun Selva Kumar


2 Answers

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(', '));
like image 69
hindmost Avatar answered Jan 14 '23 00:01

hindmost


There are a lot of ways one could go about this. The answers so far assume you want to modify the existing objects but the question doesn't specify; the word "filter" suggests maybe not. So if you want to create a new filtered object, rather than mutate the existing one(s), you might employ a reduce function. You said your key list is a string, but for the sake of keeping the examples clean, let's assume you just do str.split(',') or similar so it's already an array before passing it to these functions.

ES5

function createObjectFilter(keys) {
  return function(obj) {
    return keys.reduce(function(acc, key) {
      acc[key] = obj[key];
      return acc;
    }, {});
  };
}

var myFilter = createObjectFilter([ 'a', 'b' ]);

var filteredObject = myFilter(object);

ES6

const createObjectFilter = keys => obj => keys.reduce((acc, key) => {
  acc[key] = obj[key];
  return acc;
}, {});

const myFilter = createObjectFilter([ 'a', 'b' ]);

const filteredObject = myFilter(object);

Now, the createObjectFilter function returns the actual filter function based on a given list of keys. You could make it "all in one", instead, but the advantage of this approach is that it becomes possible to reuse your filters in more situations. For example:

const filteredObjects = unfilteredObjects.map(myFilter);
like image 26
Semicolon Avatar answered Jan 13 '23 22:01

Semicolon