tonycor nikolauos
tonycor nikolauos

Reputation: 475

counting selected words into a new object in JS

I have:

function selectMutualKeys(arr, obj) {
  var o = {};
  for (var i = 0; i < arr.length; i++) { 
    var key = arr[i];  
    if ( arr[i] === obj[key] ) {
      o[key] = obj[key] ;
    }
  }
  return o;
}

Should return a new object with only the mutually present keys/values:

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

What am i missing?

Upvotes: 1

Views: 26

Answers (2)

Nina Scholz
Nina Scholz

Reputation: 386654

You could check, if the key is a property of the object, with the in operator, then assign the value.

if (key in obj) {

function selectMutualKeys(arr, obj) {
    var o = {}, key, i;
    for (i = 0; i < arr.length; i++) { 
        key = arr[i];  
        if (key in obj) {
            o[key] = obj[key];
        }
    }
    return o;
} 

var arr = ['a', 'c', 'e'],
    obj = { a: 1, b: 2, c: 3, d: 4 },
    out = selectMutualKeys(arr, obj);

console.log(out); // { a: 1, c: 3 }

Upvotes: 1

Tareq
Tareq

Reputation: 5363

function selectMutualKeys(arr, obj) {
var o = {};
for (var i = 0; i < arr.length; i++) { 
  var key = arr[i];  
  if (obj[key] ) {
      o[key] = obj[key] ;
  }
}
return o;
} 


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

Upvotes: 0

Related Questions