Click here to Skip to main content
15,907,395 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I was doing in exercise in which I had to write a function called select. Given an array and object, I had to return a new object whose properties included only those which were common among the array and the original object. For example:

JavaScript
var arr = ['a', 'c', 'e'];
var obj = {
  a: 1,
  b: 2,
  c: 3,
  d: 4
};
var output = select(arr, obj);
console.log(output); // --> { a: 1, c: 3 }


The code below 'works,' but I'm trying to understand how newObject[search] = obj[search] yields the right results in newObject.


JavaScript
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 I have tried:

I've run this code through the debugger in Google dev tools multiple times. My best understanding is that obj[search] reaches all the way back up to the 'keys' variable to find out how it relates to the 'search' variable.

Thanks sincerely for your help!
Posted
Updated 27-Apr-18 14:07pm
v2

1 solution

JavaScript
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.
 
Share this answer
 
v4

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900