jmt jmt - 1 year ago 76
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 Source

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=""></script>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download