Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to creates an object with only the listed keys?

Tags:

javascript

Creates an object composed of the picked source properties.

Parameters

  • source - Any JavaScript Object
  • keys - An array of JavaScript Strings

Return 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

like image 627
tryingToBeBetter Avatar asked Dec 05 '25 04:12

tryingToBeBetter


1 Answers

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 }
like image 136
Barmar Avatar answered Dec 06 '25 17:12

Barmar