'How to sum of two value of JSON object?

{
  "order": [
    {
      "billDate": "1-apr-2016",
      "stock": 2,
      "Qty": 4,
      "Amount": 4500,
      "Available": '',
    },
    {
      "billDate": "1-may-2016",
      "stock": 3,
      "Qty": 2,
      "Amount": 4500,
      "Available": '',
    }
  ]
}

I have an array which is sorted by billDate . now i need to add my first Object date Stock (i.e 2) to next object Qty and add into Available field .

Expected Result:

{
  "order": [
    {
      "billDate": "1-apr-2016",
      "stock": 2,
      "Qty": 5,
      "Amount": 4500,
      "Available": 0,
    },
    {
      "billDate": "1-may-2016",
      "stock": 3,
      "Qty": 2,
      "Amount": 4500,
      "Available": 4,
    }
  ]
}

First Object Stock is 2 and next object Qty is 2 so Available is 4.How to add like above approach ?

I have tried like this

var totalTaxes = order.reduce(function (sum, tax) {
  return sum + (tax.Qty + tax.stock);
}, 0);


Solution 1:[1]

You don't want reduce for this at all. If your intention is to create an array of the same length with different values, you want map

const { order } = {"order":[{"billDate":"1-apr-2016","stock":2,"Qty":4,"Amount":4500,"Available":""},{"billDate":"1-may-2016","stock":3,"Qty":2,"Amount":4500,"Available":""}]}

const result = {
  order: [
    {...order[0], Available: 0}, // first entry with Available: 0
    ...order.slice(1).map((ord, i) => ({ // map the rest
      ...ord,
      Available: ord.Qty + order[i].stock // calculate new Available
    }))
  ]
};

console.log(result);
.as-console-wrapper { max-height: 100% !important; }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Phil