简体   繁体   English

如何遍历 JSON 并向对象添加值

[英]How to loop through JSON and add values to object

So I am having trouble figuring out how to create an array with two objects, looping through my object and adding some values to those objects in Javascript.所以我无法弄清楚如何创建一个包含两个对象的数组,循环遍历我的对象并在 Javascript 中向这些对象添加一些值。 Currently I have the following mock response:目前我有以下模拟响应:

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"
              }
            ]
          }

I would like to have an array with two objects.我想要一个包含两个对象的数组。 One for the first error message("Ship to home...") and another for the second error message("Pickup at Seller...").一个用于第一条错误消息(“运送到家...”),另一个用于第二条错误消息(“在卖家取货...”)。 I would like to then loop through the JSON and add each "orderItemIds" to there respective object.然后我想遍历 JSON 并将每个“orderItemIds”添加到相应的对象中。 For example, 10315031,10315032 would go to the first object and 10222222, 10333333 to the second.例如,10315031,10315032 将转到第一个对象,而 10222222、10333333 将转到第二个对象。

You can use reduce to loop through your errors and use the errorMessage property as a key您可以使用 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
}, {})

Let me know if this does answer your question如果这确实回答了您的问题,请告诉我

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM