Young Al Capone
Young Al Capone

Reputation: 399

javascript How to count rows in array inside an object and then add result to object?

I'm working with ReactTs since 3 months and now I'm trying to create a simple table to put some response results.

ReactTs Action file:

const response = await dropOffService
  .getDropOffOrders(
    page,
    count,
    filters,
    sorting,
  );
if (!dropOffOrdersResponse) return;
handleServerResponse(Action.LIST, { dropOffOrdersResponse }, dispatch);

the point is I would like to show the total of order pieces of every element of principal array. This information is individually available in response but I would like to add a new field in my response, a easy way to show this information in table column.

API Response:

const res = {
  "data": [ {
    "id": 1,
    "trackingId": "D-1",
    "documentLink": null,
    "createdAt": "2021-09-03T01:40:46.508Z",
    "originNode": {
      "id": 1,
      "name": "Principal Node"
    },
    "orders": [ {
      "id": 1,
      "trackingId": "1500912172021",
      "address": "Fictional Address 123",
      "zipCode": "5009",
      "province": "Cordova",
      "state": "Cordova",
      "generatedShipment": true,
      "shipper": {
        "id": 1,
        "name": "unknown Shipper",
        "province": "Cordova",
        "city": "Cordova",
        "address": "Fictional Address",
        "isCashOnDelivery": false,
        "numberOfDays": null,
        "paymentMethod": null,
        "fixedAmount": null,
        "piecePercentage": null,
        "email": null,
        "surplusAllowed": null
      },
      "pieces": [
        { "id": 1 },
        { "id": 4 },
        { "id": 3 },
        { "id": 2 }
      ]
    } ],
    "container": null
  } ],
  "count": 1,
  "total": 1,
  "page": 1,
  "pageCount": 1,
};

I would like to count records in "Pieces" field and then add the result in a new field named piecesTotal below to "container" field. How is it possible to do?

Expect result:

.
.
.
{
          "id": 2
        }
      ]
    }],
    "container": null,
    "PIECESTOTAL": 4
  ],
    "count": 1,
    "total": 1,
    "page": 1,
    "pageCount": 1 
}

I think this operation could be do in action response.

Thanks!!!

Upvotes: 0

Views: 332

Answers (1)

Hoda Arezoudar
Hoda Arezoudar

Reputation: 400

data.forEach(element => {
 var totalCount = 0
    element.order.forEach(order => {
        totalCount += order.pieces.length
    });
  element.piecesTotal = totalCount
});

Upvotes: 1

Related Questions