What do you do when you need to take some fields from an object with many fields to make a new object?

What if some of these fields might not be there? Do you need to judge each field once? Here’s one from Stack Overflow (🤦️) :

const pick = (. props) = >
  ob => props.reduce((other, e) = >ob[e] ! = =undefined ? { ...other, [e]: ob[e] } : other, {});
Copy the code

The pick method is a Currified function that, after passing in the required fields, returns a function that extracts the corresponding fields of the input object into the new object and filters out undefined values because the input object does not define a key.

The call method is as follows:

const source = { a: 1.b: 2.c: 3 };
const result = pick('a'.'c'.'d')(source);  // { a: 1, c: 3 }
Copy the code

Rewrite this method to make sense:

function pickerGenerate(keys) {
  return function(ob) {
    const result = {};
    keys.forEach(key= > {
      if(ob[key] ! = =undefined) { result[key] = ob[key]; }});returnresult; }}// Generate a picker function for a specific field
const specifiedPicker = pickerGenerate(['a'.'c'.'d']);
const source = { a: 1.b: 2.c: 3 };
const result = specifiedPicker(source); // { a: 1, c: 3 }
Copy the code