ganesh kaspate
ganesh kaspate

Reputation: 2685

Group the data in an array and get the sum from the array of object values

I am new to react and javascript. Here I am trying to use the lodsh function.

I have an array of object which looks like ,

const data = [{
"Id": "1",
          "testone": 100,
          "test": 40,
          "Original": {
            "Id": "11"
          },
          "__Parent__": {
            "Id": "20",
            "Status": "INP"
          }
}, {
"Id": "2",
          "testone": 120,
          "test": 20,
          "Original": {
            "Id": "10"
          },
          "__Parent__": {
            "Id": "21",
            "Status": "Book"
          }
},{
"Id": "3",
          "testone": 110,
          "test": 140,
          "Original": {
            "Id": "11"
          },
          "__Parent__": {
            "Id": "20",
            "Status": "INP"
          }
}, {
"Id": "4",
          "testone": 100,
          "test": 40,
          "Original": {
            "Id": "11"
          },
          "__Parent__": {
            "Id": "20",
            "Status": "Val"
          }
}]

Here, I have one function which has the product Id . which I am passing from another function =>

cont value = (PID, data) => {
    
 
}

So, this function ,

I need do sum , where first I need to take all the object which has the same Id as PID. The Id from object is to be Original.ID. If these matches then after that ,I need to check the status of that objects like , is status is either INP or BOOK then for summation need to take the

testone key value or else need to take the `test` key value.

So, In the given example it will be like ,

Id is 11 which is passed to a function and in the given object 3 objects where it matches.

Now,

while returning sum it will be like ,

100 + 100 + 40 which will be 240.

So, How do I do this . thanks .

Upvotes: 2

Views: 57

Answers (1)

Rokata
Rokata

Reputation: 1229

I think it's best to do it with Array.reduce if you support IE9 and after.

const sum = data.reduce((total, item) => {
    if (item.Original.Id !== PID) return total;

    const { status, testone, test } = item;
    let addition = 0;

    if (status === "INP") addition = testone;
    else if (status === "BOOK") addition = test;
    
    return total + addition;
}, 0);

Upvotes: 1

Related Questions