Dynamically generate object from another object with value mapping

Dynamically generate object from another object with value mapping

When working with TypeScript, there may be times when you need to dynamically generate a new object based on an existing object, but with some values mapped or transformed. In this blog post, we will explore different solutions to achieve this using TypeScript.

Solution 1: Using a for…in loop

One way to dynamically generate a new object with value mapping is by using a for…in loop. This loop allows you to iterate over the properties of an object and perform operations on them.

Here’s an example:

const sourceObject = {
  name: 'John',
  age: 30,
  city: 'New York'
};

const mapping = {
  name: 'fullName',
  age: 'yearsOld',
  city: 'location'
};

const targetObject = {};

for (const key in sourceObject) {
  if (key in mapping) {
    targetObject[mapping[key]] = sourceObject[key];
  }
}

console.log(targetObject);

The output of the above code will be:

{
  fullName: 'John',
  yearsOld: 30,
  location: 'New York'
}

Solution 2: Using Object.entries() and reduce()

Another approach is to use the Object.entries() method to get an array of key-value pairs from the source object, and then use the reduce() method to transform and map the values based on the provided mapping.

Here’s an example:

const sourceObject = {
  name: 'John',
  age: 30,
  city: 'New York'
};

const mapping = {
  name: 'fullName',
  age: 'yearsOld',
  city: 'location'
};

const targetObject = Object.entries(sourceObject).reduce((acc, [key, value]) => {
  if (key in mapping) {
    acc[mapping[key]] = value;
  }
  return acc;
}, {});

console.log(targetObject);

The output of the above code will be the same as the previous solution:

{
  fullName: 'John',
  yearsOld: 30,
  location: 'New York'
}

These are two possible solutions to dynamically generate a new object from another object with value mapping using TypeScript. Choose the solution that best fits your specific use case and enjoy the flexibility and power of TypeScript!

That’s it for this blog post! We hope you found it helpful. If you have any further questions or suggestions, feel free to leave a comment below.

Happy coding!


Posted

in

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *