function select(arr, obj) {
var newObject = {};
var keys = Object.keys(obj);
for (var i = 0; i < arr.length; i++) {
var search = arr[i];
if (keys.indexOf(search) !== - 1) {
newObject[search] = obj[search];
}
}
return newObject;
}
What's happening is you setup a variable which holds all the keys of the
obj
parameter -
keys
. You then iterate through the
arr
parameter checking whether each element (
search
) is in the
keys
list (
indexOf
returns -1 if no key is found). If the element is in the list you then move the value from
obj
into
newObject
.
The assignment statement given your example will execute
newObject['a'] = obj['a'];
and
newObject['c'] = obj['c'];
.
The
MDN[
^] has a great JS guide and reference materials.