learninghowtocode learninghowtocode -4 years ago 165
Javascript Question

Return a new object whose properties are those in the given object and whose keys are present in the given array.

:) I need to return a new object whose properties are those in the given object and whose keys are present in the given array.

code attempt:

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

function select(arr, obj) {
var result = {};
var array = [];
for (var key in obj){
array.push(key);
}
var num = arr.length + obj.length;
for (var i = 0; i < num; i++) {
for(var j = 0; j < num; j++) {
if (arr[i] === array[j]) {

result.array[i] = obj.arr[i];
}
}
}
return result;
}


(incorrect) result:

{}


desired result:

// --> { a: 1, c: 3 }


Any advice? Thank you! :)

Answer Source

Longer, but more readable version:

var arr = ['a', 'c', 'e'],
    obj = {a:1,b:2,c:3,d:4},
    hash = {};
    
arr.forEach(function(v){     //iterate over each element from arr
  Object.keys(obj).some(function(c){  //check if any key from obj is equal to iterated element from arr
    if (v == c) {
      hash[v] = obj[c]; //if it is equal, make a new key inside hash obj and assign it's value from obj to it
    }
  });
});

console.log(hash);

Short version:

var arr = ['a', 'c', 'e'],
    obj = {a:1,b:2,c:3,d:4},
    hash = {};
    
arr.forEach(v => Object.keys(obj).some(c => v == c ? hash[v] = obj[c] : null));

console.log(hash);

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download