我有一个Json数组,例如:
[{"name":"ip","children":{"label":"ip","value":"","type":"text","validation":"{ required: true}"}}
,{"name":"test","children":{"label":"test","value":"","type":"text","validation":"{ required: true}"}}
,{"name":"join","children":{"label":"join","value":"","type":"text","validation":"{ required: true}"}}
,{"name":"myform","children":{"label":"myform","value":"","type":"text","validation":"{ required: true}"}}]
我应该将一个对象传递给这样的组件
export const person = {
ip: {
label: 'ip',
value: '',
type: 'text',
validation: { required: true }
},
test: {
label: 'test',
value: '',
type: 'text',
validation: { required: true }
},
join: {
label: 'join',
value: '',
type: 'text',
validation: { required: true }
},
myform: {
label: 'myform',
value: '',
type: 'text',
validation: { required: true }
}
}
我该怎么做?
答案 0 :(得分:5)
您可以使用.reduce
函数。
它将遍历数组,并允许您将其转换为单个值(在本例中为对象)。
(请记住,在您的原始数组中,validation
是字符串,而不是对象)
let arr = [{"name":"ip","children":{"label":"ip","value":"","type":"text","validation":"{ required: true}"}}
,{"name":"test","children":{"label":"test","value":"","type":"text","validation":"{ required: true}"}}
,{"name":"join","children":{"label":"join","value":"","type":"text","validation":"{ required: true}"}}
,{"name":"myform","children":{"label":"myform","value":"","type":"text","validation":"{ required: true}"}}]
// Transform the array
let result = arr.reduce((res, item) => {
// Add the value into the result object
res[item.name] = item.children;
return res;
}, {});
console.log(result);
有关简化here
的更多详细信息