如何将我的Json数组转换为angular 5中的对象

时间:2018-08-28 06:03:18

标签: angular typescript

我有一个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 }
    }
}

我该怎么做?

1 个答案:

答案 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

的更多详细信息