[英]How to loop through JSON and add values to object
所以我無法弄清楚如何創建一個包含兩個對象的數組,循環遍歷我的對象並在 Javascript 中向這些對象添加一些值。 目前我有以下模擬響應:
const mockResponse =
{
"errors": [
{
"errorKey": "ERROR_NO_DELIVERY_OPTIONS",
"errorParameters": [
{
"errorMessage": "ERROR_DELIVERY_OPTIONS_YOU_SELECTED_NOT_AVAILABLE_NOW",
"partNumbers": [
19308033,
19114798
]
},
{
"errorMessage": "Ship to Home not available for these orderItemId",
"orderItemIds": [
10315031,
10315032
],
"availableShipModeId": 13203
},
{
"errorMessage": "Pickup At Seller not available for these orderItemIds",
"orderItemIds": [
10222222,
10333333
],
"availableShipModeId": 13203
}
],
"errorMessage": "ERROR_NO_DELIVERY_OPTIONS",
"errorCode": "ERROR_NO_DELIVERY_OPTIONS"
}
]
}
我想要一個包含兩個對象的數組。 一個用於第一條錯誤消息(“運送到家...”),另一個用於第二條錯誤消息(“在賣家取貨...”)。 然后我想遍歷 JSON 並將每個“orderItemIds”添加到相應的對象中。 例如,10315031,10315032 將轉到第一個對象,而 10222222、10333333 將轉到第二個對象。
您可以使用 reduce 來遍歷錯誤並使用 errorMessage 屬性作為鍵
const result = mockResponse.errors[0].errorParameters.reduce((prev, item) => {
const { errorMessage, orderItemIds } = item;
if (prev[errorMessage]) {
prev[errorMessage] = [...prev[errorMessage], ...orderItemsIds];
} else {
prev[errorMessage] = orderItemIds
}
return prev
}, {})
如果這確實回答了您的問題,請告訴我
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.