Skip to content
the poor coder

loadash pick property from object by different name

Poor Man
Published
Reading time
2 min read
On this page

How to use Loadash to pick a property from an object by a different name#

If you are working with objects in JavaScript, you may come across a situation where you need to pick a property from an object by a different name. This can be achieved using Loadash library.

Using Loadash Pick Method#

To pick a property from an object using a different name, we can use Loadash's pick method. The pick method returns a new object with the specified properties picked from the original object.

For example, consider the following object:

Text

const user = {
  name: 'John Doe',
  age: 30,
  email: 'johndoe@example.com'
};

If we want to pick the 'name' property from the user object and rename it as 'fullName', we can use the pick method as follows:

Text

const fullName = _.pick(user, ['name']);
const userWithFullName = { ...user, fullName };

The above code will create a new object with the 'name' property picked from the user object and renamed as 'fullName'. This new object will also contain all other properties of the original object.

Using Loadash MapKeys Method#

Another way to achieve the same result is by using Loadash's mapKeys method. The mapKeys method creates a new object with the keys of the original object mapped to new keys.

For example, consider the following object:

Text

const user = {
  name: 'John Doe',
  age: 30,
  email: 'johndoe@example.com'
};

If we want to rename the 'name' property as 'fullName', we can use the mapKeys method as follows:

Text

const renamedUser = _.mapKeys(user, (value, key) => {
  if (key === 'name') {
    return 'fullName';
  }
  return key;
});

The above code will create a new object with the 'name' property renamed as 'fullName'. This new object will also contain all other properties of the original object.

Conclusion#

Both the pick and mapKeys methods of Loadash can be used to pick a property from an object by a different name. The choice of method depends on the specific use case.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC