[英]What is the most efficient way to transform model of objects?
I have an initial static model on front-end side.我在前端有一个初始静态模型。 It looks like this:
它看起来像这样:
[
{
completed: false,
id: 0,
index: 0,
isNavigationAllowed: true,
name: 'Test1',
},
{
completed: false,
id: 1,
index: 1,
isNavigationAllowed: false,
name: 'Test2',
},
{
completed: false,
id: 2,
index: 2,
isNavigationAllowed: false,
name: 'Test3',
},
]
In short, my app behave like a wizard page, so when user clicks 'Next' button, I should change the model (and don't mutate it).简而言之,我的应用程序就像一个向导页面,所以当用户单击“下一步”按钮时,我应该更改模型(并且不要改变它)。 I use the following transform function:
我使用以下转换函数:
function transformWizardStepsModelForNext(step, wizardStepsModel) {
return wizardStepsModel.reduce((accumulator, currentValue) => {
if (step === currentValue.index) {
let newValue = { ...newValue }
newValue.completed = true
newValue.isNavigationAllowed = false
return [...accumulator, newValue]
}
return [...accumulator, currentValue]
}, [])
}
I should change two objects in my model (without mutation) on every user 'next' and 'previous' button clicks.我应该在每个用户点击“下一个”和“上一个”按钮时更改模型中的两个对象(没有突变)。 So, after first click, I should change: completed = true, isNavigationAllowed = false fields from the first object, and isNavigationAllowed = true field from the second object.
因此,在第一次单击后,我应该更改:第一个对象的 completed = true、isNavigationAllowed = false 字段,以及第二个对象的 isNavigationAllowed = true 字段。 The same logic, but vice versa on the click 'previous' button.
相同的逻辑,但在单击“上一个”按钮时反之亦然。 I've choose reduce array method for this transformation, but it looks like I can work only with one object.
我为此转换选择了 reduce array 方法,但看起来我只能处理一个对象。 The question is: What is the most efficient way for transformation here on your point of view?
问题是:在您看来,最有效的转型方式是什么?
You can use map function instead of reduce您可以使用 map 函数而不是 reduce
wizardStepsModel.map(currentValue => {
if (step === currentValue.index) {
return {
...currentValue,
completed: true,
isNavigationAllowed: false
}
} else if (step + 1 === currentValue.index) {
return {
...currentValue,
isNavigationAllowed: true
}
}
else return currentValue
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.