Write a function called "select".
Given an array and an object, "select" returns a new object whose properties are those in the given object AND whose keys are present in the given array.
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 }
My Solution:
function select(arr, obj) {
for (var k in obj) {
return arr.reduce((o, c) => {
if (obj.hasOwnProperty(c)) {
o[c] = obj[c]
}
return o
}, {})
}
}
var array = ['a', 'c', 'e'];
var object = {
a: 1,
b: 2,
c: 3,
d: 4
};
console.log(select(array, object));
My solution is working, but I have a feeling that I'm not using the best practices or most eloquent code. For example I'm using a for/in to search the object, but I never use the 'k' from for (var k in obj). Any tips would be appreciated.
Iterate the array with Array#reduce and pluck all properties that exist on the object to a new object: