DEV Community

ben hultin
ben hultin

Posted on • Updated 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!

Top comments (0)