I have a JSON object (comes from my multi-step form) that looks like the following:
[
{
"title": "Personal Details",
"fields": [
{
"label": "FirstName",
"value": "John"
},
{
"label": "SecondName",
"value": "Doe"
},
{
"label": "Age",
"value": "22"
}
]
},
{
"title": "Address",
"fields": [
{
"label": "City",
"value": "New York"
},
{
"label": "ZipCode",
"value": "10001"
},
{
"label": "County",
"value": "NY County"
},
{
"label": "State",
"value": "NY"
}
]
}
]
I want to loop over this object and create a new object to use it as a formData object using "label" and "value" to write this data in my database. So the new object should look like the following:
{
FirstName: "John",
SecondName: "Doe",
Age: "22",
City: "New York",
Zipcode: "10001"
...
}
How to realize this in a loop or with forEach ? Thanks in advance.
CodePudding user response:
Have a look at the following snippet:
const test = [
{
"title": "Personal Details",
"fields": [
{
"label": "FirstName",
"value": "John"
},
{
"label": "SecondName",
"value": "Doe"
},
{
"label": "Age",
"value": "22"
}
]
},
{
"title": "Address",
"fields": [
{
"label": "City",
"value": "New York"
},
{
"label": "ZipCode",
"value": "10001"
},
{
"label": "County",
"value": "NY County"
},
{
"label": "State",
"value": "NY"
}
]
}
]
const result = {};
test.forEach(obj => {
obj.fields.forEach(field => {
result[field.label] = field.value;
});
});
console.log(result);