我有一个很大的 JS 对象,我将其提供给工厂。原始对象包含数组中的字符串,这些字符串是工厂的参数。
我想将代码缩短到尽可能短,并希望能够发挥作用。
到目前为止我所拥有的:
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);
最佳答案
这里没什么可做的,但我会去
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)
},
]
};
关于javascript - 将字符串替换为嵌套数组中的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50160855/