How dynamically add property to the object?

Hello, I’m trying to solve such exercise


Notes:
* If keys are present in the given array, but are not in the given object, it should ignore them. 
* It does not modify the passed in object.

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 }

here is my trying to solve it

function select(arr, obj) {
  // your code here
  let newObject={};
  let newArr = Object.keys(obj);

  
  for(let i = 0; i < newArr.length; i++){
    for(let j = 0; j < arr.length; j++){
      if(newArr[i] === arr[j]){
        newObject[i] = obj[i];
      }
    }
  }
  
  console.log(newObject); //--> { 0: undefined, 2: undefined }
  
}
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 output of function --> { 0: undefined, 2: undefined }
My question is how correctly dynamically add the propertys to the newObject?

newObject[i] = obj[i];

this line is the culprit. Instead of passing the indexes, you should be passing the corresponding key value pairs. You have a key array arr and an object obj to get the values from.

Can you now tell how to proceed?

1 Like