[英]How to rewrite the form data key value inside the array [] from angular6 reactive dynamic form
我在 angular6 项目中创建了 angular 反应动态形式。 我得到的表单值如下所示:
const formValues = {
name: 'test1',
age: '02/08/1985',
product: {
apple: false,
orange: true,
banana: true,
graps: false
},
sex: 'Male',
city: null,
address: null
}
如果键值为空,我将显示空数组,如果它有值,将显示数组内的值,产品键值为真,我将仅在产品数组中显示真值键名。 我的期望值是这样的:
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])
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.