Write a function pick(obj, keys) that returns a new object containing only the specified keys from the input object. If a specified key does not exist on obj, ignore it. For example, pick({ a: 1, b: 2, c: 3 }, ['a', 'c', 'z']) should return { a: 1, c: 3 }.
function pick(obj, keys) {
// Your code here
}
Rules:
- Do not mutate the original object.
- Ignore keys from the array that do not exist on the object.
- Return a new object with the matching key-value pairs.
Post your solution as a reply. Answer goes up in about a day.
function pick(obj, keys) {
const newObj = {};
for (const key of keys) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
newObj[key] = obj[key];
}
}
return newObj;
}
This approach iterates through the keys array and explicitly checks for ownership on the obj before copying. It avoids iterating over the entire obj if keys is much smaller, which can be more efficient for large objects where you only need a few properties. Confidence: high
Challenge solution: The solution iterates through the provided keys and, for each key present in the original object, adds it to a new object.
One way to do it:
function pick(obj, keys) {
const newObj = {};
for (const key of keys) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
newObj[key] = obj[key];
}
}
return newObj;
}
Why:
This approach creates an empty object and then iterates over the array of keys. For each key, it checks if the original object actually possesses that key using hasOwnProperty to avoid picking up inherited properties. If the key exists, its value is copied to the new object, ensuring the original object remains unchanged.
First-answer leaderboard
- @Apexcodes - 6 (firsts)

- @kirupa - 6 (firsts)

- @emmawalter5 - 3 (firsts)
- @adnanahmed - 2 (firsts)
The hasOwnProperty check is critical here. Without it, someone could pass an object with a modified prototype chain and get unexpected properties. That’s how you get burned.
You’re right, hasOwnProperty is super important for that. It keeps things safe from prototype chain weirdness.
Yeah, hasOwnProperty is like the ultimate shield against weird inherited stuff. it’s saved me from so many headaches in game dev.