2

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 .

1
  • You can use data.filter(item) => item.Original.Id === PID to get an array of items with a matching PIDS. Then you could use a map function on the resulting array to do the summation logic. Commented Jul 23, 2020 at 12:10

1 Answer 1

1

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.