我有以下输入:
schema: [{
fields: [{
name: 'name',
type: 'text',
col: 10,
value: ''
}, {
name: 'description',
type: 'text',
col: 2,
value: ''
}]
}, {
fields: [{
name: 'password',
type: 'text',
col: 8,
value: ''
}, {
name: 'confirmPassword',
type: 'textarea',
col: 4,
value: ''
}]
}],
然后我像这样设置嵌套数组对象的值
:
updateField (name, value) {
this.schema.forEach((formGroup, index) => {
formGroup.fields.forEach(field => {
if (field.name === name) field.value = value
})
})
},
有没有办法避免使用两个嵌套的forEach
? (不使用像 Lodash 这样的库?)
最佳答案
您可以使用 reduce 和展开运算符来合并您的数组,然后在您的平面数组上使用 forEach 来展平您的数组:
updateField (name, value) {
this.schema
.reduce((memo, item) => [...memo, ...item.fields], [])
.forEach(field => {
if (field.name === name) field.value = value;
});
}
关于javascript - 如何展平嵌套的 forEach?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43991397/