简体   繁体   中英

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. 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. For example, 10315031,10315032 would go to the first object and 10222222, 10333333 to the second.

You can use reduce to loop through your errors and use the errorMessage property as a key

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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