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?

1

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

1 Comment

@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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.