Reputation: 395
I have a form in react which has multiple form fields. The user inputs the values in the form fields and it is stored in the state of the component. Now I want to display the state of the component in a particular way.
So right now my state looks like this:
{
"groups": [
{
"typeA": [
{
"name": "abc"
},
{
"number": "13,14"
}
],
"typeB": [
{
"country": "xyz"
},
{
"date": "2019-05-14"
}
]
}
]
}
However, I want an output like this:
groups: {
"typeA": [[abc],[13,14]],
"typeB": [[2019-05-14],[xyz]]
}
I want to know how to manipulate the values stored in the state to look like my desired output. I am a beginner in react and dont know how to manipulate the state values. Please can anybody help me out with this
Upvotes: 0
Views: 43
Reputation: 1911
Here you can use reduce on groups.
var state = {
"groups": [
{
"typeA": [
{
"name": "abc"
},
{
"number": "13,14"
}
],
"typeB": [
{
"country": "xyz"
},
{
"date": "2019-05-14"
}
]
}
]
}
var output = state.groups //iterating over groups using reduce
.reduce((final, s)=> { // final:-output object , s:- group array element
const values = Object.keys(s) // iterating over key element keys e.g. "typeA"
.reduce((out, o)=> { // out: value of key, o: element of keyArray e.g state.groups.typeA
out[o] = s[o].map(k => Object.values(k)) //returning values in array
return out;
}, {})
final = {...final, ...values} // update the output
return final;
}, {})
console.log(output) // "{"typeA":[["abc"],["13,14"]],"typeB":[["xyz"],["2019-05-14"]]}"
Upvotes: 1