[英]How to convert my Json array to object in angular 5
I have a Json array Such as this: 我有一个像这样的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}"}}]
and I should be pass one object to component like this 我应该将一个对象传递给这样的组件
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 }
}
}
how can I do this? 我怎样才能做到这一点?
You can use the .reduce
function for this. 您可以为此使用
.reduce
函数。
It will iterate through an array and allow you to transform it into a single value (in this case an object). 它将遍历数组,并允许您将其转换为单个值(在这种情况下为对象)。
( Bear in mind that in your original array, the validation
is a string, not an object ) (请记住,在您的原始数组中,
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.