Dynamically create an object from another one
ben hultin
Posted on May 4, 2023
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
}
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
}
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
};
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
{}
);
when we console.log(myLabels)
we get the following outout
If you have any questions how this went together, feel free to leave a comment.
Thanks for reading!
💖 💪 🙅 🚩
ben hultin
Posted on May 4, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
webdev Craft Stunning Interactive Data Visualizations: A Deep Dive into D3.js and Plotly
June 28, 2023