How does the function know how to iterate through all the keys in "obj"? Is this a feature already written in the objects element? In the if statement obj is iterating through all the elements in arr (currentElement =arr[i]). There is no loop is no loop to iterate through all the keys in obj. How is it able to do that without a loop?
(obj[currentElement] !== undefined)
var arr = ['a', 'c', 'e'];
var obj = {
a: 1,
b: 2,
c: 3,
d: 4
};
function select(arr, obj) {
// initialize newObj to empty object;
var newObj = {};
//create for loop to to iterate through current element in arr
for (var i=0; i<arr.length; i++){
var currentElement = arr[i];
// if currentElement (key) exists in obj
if (**obj[currentElement] !== undefined**){
// currentElement in newObj is equal to obj value
newObj[currentElement] =obj[currentElement];
}
}
return newObj;
}
var output = select(arr, obj);
console.log(output); // --> { a: 1, c: 3 }
Thanks.