如何从angular6反应动态表单重写数组[]内的表单数据键值



我已经在angular6项目中创建了角反应动力学形式。我得到的表单值如下:

const formValues = {
name: 'test1',
age: '02/08/1985',
product: {
apple: false,
orange: true,
banana: true,
graps: false
},
sex: 'Male',
city: null,
address: null
}

如果键值为null,我将显示空数组。如果它有值,我将在数组中显示值,而产品键值为true,我将仅在产品数组中显示true值的键值名称。我的期望值是这样的:

const formValues = {
name: ['test1'],
age: ['02/08/1985'],
product: ['orange', 'banana'],
sex: ['Male'],
city: [],
address: []
}

我尝试了循环和映射,但没有得到预期的结果。请帮帮我。感谢

注意:表单键&值是动态的,所以我们不知道确切的密钥名称

这将为您提供问题中的确切输出。它有点简洁,所以我将在这里进行分解

let fv = formValues, // for brevity, rename the source object
newFormValues = Object.assign(...Object.keys(fv) // our end result is an object (assign) but we'll loop through using the keys array
.map(f => ( // for each string from object.keys
{[f]: fv[f]!==null && typeof fv[f] === 'object' ?  // if the value is not null but is an object (null is also an object but will error if we don't catch it here) ...
Object.entries(fv[f]).reduce((b,a)=>!!a[1] && [...b,a[0]] || b,[])  :   // return filtered keys from that object (the products for example)
[fv[f]] // otherwise, just use the value as is, in array format
})));

const formValues = {
name: 'test1',
age: '02/08/1985',
product: {
apple: false,
orange: true,
banana: true,
graps: false
},
sex: 'Male',
city: null,
address: null
}
let fv = formValues, newFormValues = Object.assign(...Object.keys(fv).map(f => ({[f]: fv[f]===null ? null : typeof fv[f] === 'object' ?  Object.entries(fv[f]).reduce((b,a)=>!!a[1] && [...b,a[0]] || b,[]) : [fv[f]]})));
console.log(newFormValues)

你可以做:

const formValues = {
name: 'test1',
age: '02/08/1985',
product: {
apple: false,
orange: true,
banana: true,
graps: false
},
sex: 'Male',
city: null,
address: null,
}
const getValueByType = (v) => ({
string: [v],
boolean: v,
object: Object.entries({...v}).filter(([_, v]) => v).map(([k, _]) => k),
}[typeof v])
const newFormValues = Object
.entries(formValues)
.reduce((a, [k, v]) => (a[k] = getValueByType(v), a), {})

console.log(newFormValues)

每个属性都想成为数组吗???

如果你只想要一个数组;产品";你可以使用

formValuesFormatted={...this.formValues,
product:Object.keys(this.formValues.product)
.filter(x=>this.formValues.product[x])
}

最新更新