behnamhaji
behnamhaji

Reputation: 151

How to convert my Json array to object in angular 5

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?

Upvotes: 1

Views: 136

Answers (1)

user184994
user184994

Reputation: 18281

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

Upvotes: 5

Related Questions