The Pick function in JavaScript is an incredibly useful tool that enables developers to select specific values from an object and create a new object from those values. This is a functional programming technique that allows developers to extract a subset of properties from any object if the properties are available. The function is a simple and straightforward way to accomplish this task and can be used in a variety of different use cases.

The implementation of the Pick function is as follows:

const pick = (obj, keys) => {
  return keys.reduce((acc, key) => {
    if (obj.hasOwnProperty(key)) {
      acc[key] = obj[key];
    }
    return acc;
  }, {});
}

The function takes two parameters: obj, which is the original object that the new object will be created from, and keys, which is an array of keys to select into the new object.

The function uses the reduce() method to iterate over the keys array and compare them to the properties of the original obj. If the key is present in the obj, it is added to the accumulator object of the reduce function, which was initialized with {}. At the end of the reduce function, the accumulator object will be the new object and will contain only the specified properties that were in the keys array.

Let’s consider an example to understand the function’s usage. Consider the following object:

const obj = {
    id: 1,
    name: 'Salary',
    address: 'DaNang, VietNam',
    role: 'admin',
    website: 'https://lebaluong.com',
};

If we only want to select the name and website properties, we can use the pick function like this:

const selected = pick(obj, ['name', 'website']);
console.log(selected); // { name: 'Salary', website: 'https://lebaluong.com' }

In this example, the pick function creates a new object only containing the name and website properties. This is useful when we don’t want to expose sensitive information, such as the role, password, or id.

The Pick function can be used in a variety of use cases, such as when creating a new object that only contains certain properties from a database, or when working with APIs and only wanting to retrieve certain information from the response. This versatility makes the Pick function a must-have in any developer’s toolbox.

In conclusion, the Pick function in JavaScript provides a clean and efficient way to extract specific properties from an object and create a new object, without the need for complex code. It is a powerful tool that can make your development process much smoother and more efficient, so be sure to consider using it in your next project!