DEV Community

ben hultin
ben hultin

Posted on • Edited on

Dynamically create an object from another one

Here we will be discussing how to format one object type into another without duplicating the property names from the original object. Here is an example of what we are starting with:

const en = {
  catLabel: 'cat label',
  birdLabel: 'bird label',
  dogLabel: 'dog label',
  lizardLabel: 'lizard label',
  // more props we dont care about
}
Enter fullscreen mode Exit fullscreen mode

we want to create a new object with it to be used in our app:

const object = {
  cat: { label: en.catLabel },
  bird: { label: en.birdLabel },
  dog: { label: en.dogLabel },
  lizard: { label: en.lizardLabel },,
  // more props we dont care about
}
Enter fullscreen mode Exit fullscreen mode

There is some repetition going on here that we can clean up so we dont repeat ourselves so much. Lets first make a change to our original object:

const obj = {
  labels: {
    cat: 'cat label',
    bird: 'bird label',
    dog: 'dog label',
    lizard: 'lizard label'
  }
  // more props we dont care about
};
Enter fullscreen mode Exit fullscreen mode

Now lets create our new object in a way so we dont expressly call out each label:

const myLabels = Object.keys(obj.labels).reduce(
  (result, current) => ({
    // passing along object from past iterations 
    // and adding them to the next iteration in the loop
    ...result, 

    // current would refer to the 'cat' | 'bird' | 'dog' 
    // these values are obtained from Object.keys()
    [current]: {
      // we get the label value via bracket notation: [`${current}`]
      // same as obj.labels.cat or obj.labels.bird
      label: obj.labels[`${current}`]
    }
  }),
  // due to quirk in .reduce() it will skip first item in loop unless we pass in default object
  {}
);
Enter fullscreen mode Exit fullscreen mode

when we console.log(myLabels) we get the following outout

Image description

If you have any questions how this went together, feel free to leave a comment.

Thanks for reading!

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more