[英]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.