Creates an object composed of the picked source properties.
Parameters
source - Any JavaScript Objectkeys - An array of JavaScript StringsReturn Value
A new Object containing all of the properties of source listed in keys. If a key is listed in keys, but is not defined in source, then that property is not added to the new Object.
Examples
pick({ foo: 1, bar: 2, baz: 3 }, ['foo', 'baz']) // -> { foo: 1, baz: 3 }
pick({ qux: 4, corge: 5 }, ['bar', 'grault']) // -> {}
pick({ bar: 2 }, ['foo', 'bar', 'baz']) // -> { bar: 2 }
I have
function pick(source, keys) {
let result = {};
for (key in source) {
if (key === keys) {
result[key];
}
}
return result;
}
so far
You're not assigning anything to result[key], that should be result[key] = source[key].
You're not testing whether key is in keys correctly. === does exact comparison, you want to use keys.includes(key) to test inclusion.
function pick(source, keys) {
let result = {};
for (key in source) {
if (keys.includes(key)) {
result[key] = source[key];
}
}
return result;
}
console.log(pick({ foo: 1, bar: 2, baz: 3 }, ['foo', 'baz'])) // -> { foo: 1, baz: 3 }
console.log(pick({ qux: 4, corge: 5 }, ['bar', 'grault'])) // -> {}
console.log(pick({ bar: 2 }, ['foo', 'bar', 'baz'])) // -> { bar: 2 }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With