jmt jmt - 16 days ago 6
AngularJS Question

Filter object by array of property names

I have an object like so

var obj = { name1: somevalue1, name2: somevalue2, name3: somevalue3}


and an array

var arr = [name2, name3]


Both are dynamically created.
I need to filter object by array(exactly by property names, not by its values).
But so far all methods I've found are about filter by values.
So result should be

var result = {name2: somevalue2, name3: somevalue3}


I'm using angular, underscore. I need to filter it not in template, but in controller.
I appreciate any help!

Answer

You can use _.pick to "filter" the object.

var obj = { name1: "somevalue1", name2: "somevalue2", name3: "somevalue3"};
var keys = ["name1", "name2"];

console.log(_.pick(obj, keys));
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>