1

I have a Json array Such as this:

[{"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?

Krishna Rathore
  • 9,389
  • 5
  • 24
  • 48
behnamhaji
  • 151
  • 7
  • Possible duplicate of [How do I cast a JSON object to a typescript class](https://stackoverflow.com/questions/22875636/how-do-i-cast-a-json-object-to-a-typescript-class) – Ralf de Kleine Aug 28 '18 at 06:10

1 Answers1

5

You can use the .reduce function for this.

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 )

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);

More details can be found on reduce here

user184994
  • 17,791
  • 1
  • 46
  • 52
  • 1
    @behnamhaji Glad to help. Please feel free to mark the question as accepted with the green tick, which will allow others to find the solution if they have the same problem. – user184994 Aug 28 '18 at 06:48