我有一個 JSON 物件(來自我的多步驟表單),如下所示:
[
{
"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"
}
]
}
]
我想回圈這個物件并創建一個新物件以將其用作 formData 物件,使用“標簽”和“值”將此資料寫入我的資料庫中。所以新物件應該如下所示:
{
FirstName: "John",
SecondName: "Doe",
Age: "22",
City: "New York",
Zipcode: "10001"
...
}
如何在回圈中或使用 forEach 實作這一點?提前致謝。
uj5u.com熱心網友回復:
看看下面的代碼片段:
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);
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/530824.html
上一篇:制作逐行條件列
