Exercise
Implement a function, pick
, that takes in a JavaScript object and zero or more property names. It must return a copy of the given object that contains only the given property names.
const user = { name: "Ali", lastname: "Madooei", affiliation: "JHU", username: "amadooe1" }; // TODO Implement the pick function const result = pick(user, "name", "lastname"); console.log(result); // -> {"name":"Ali","lastname":"Madooei"}
Solution
function pick(object, ...keys) {
let result = {};
for (let i = 0; i < keys.length; i++) {
result[keys[i]] = object[keys[i]];
}
return result;
}
Here is another version which uses function expression and it is (technically) a single statement!
const pick = (object, ...keys) => Object.keys(object)
.filter(key => keys.includes(key))
.reduce((result, key) => ({...result, [key]:object[key]}), {});