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"}
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(', '));
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.
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);
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With