Reputation: 11755
I have a large JS object which I feed to a factory. The original object contains strings in an array which are a parameter for the factory.
I would like to shorten the code to as short as possible and hopefully be functional.
What I have so far:
const myConfigObject = {
label: 'something',
children: [
{
id: 'one',
style: 'some style',
children: ['key1', 'key2']
},
{
id: 'two',
style: 'some other style',
children: ['key3', 'key4']
},
]
}
function DummyFactory (key) {
return {
id: key,
data: 'generated stuff'
};
}
// How to optimize this call?
myConfigObject.children.forEach(child => {
child.children = child.children.map(subChild => DummyFactory(subChild))
});
console.log(myConfigObject);
Upvotes: 0
Views: 402
Reputation: 10975
To achieve expected use below option of even avoiding DummyFactory
myConfigObject.children.forEach(child => {
child.children = child.children.map(subChild=> {
return {
"id":subChild,
"data": 'generated stuff'
}
})
});
code sample - https://codepen.io/nagasai/pen/VxWJYd?editors=1010
const myConfigObject = {
label: 'something',
children: [
{
id: 'one',
style: 'some style',
children: ['key1', 'key2']
},
{
id: 'two',
style: 'some other style',
children: ['key3', 'key4']
},
]
}
myConfigObject.children.forEach(child => {
child.children = child.children.map(subChild=> {
return {
"id":subChild,
"data": 'generated stuff'
}
})
});
console.log(myConfigObject);
Upvotes: 0
Reputation: 14992
Trying to shortening:
myConfigObject.children.forEach(
child => child.children = child.children.map(DummyFactory));
Upvotes: 1
Reputation: 665101
There's not much to do here, but I would go for
function DummyFactory(key) {
return {
id: key,
data: 'generated stuff'
};
}
const myConfigObject = {
label: 'something',
children: [
{
id: 'one',
style: 'some style',
children: ['key1', 'key2'].map(DummyFactory)
},
{
id: 'two',
style: 'some other style',
children: ['key3', 'key4'].map(DummyFactory)
},
]
};
Upvotes: 2