繁体   English   中英

计算嵌套 object 数组中的键值

[英]Count key values from a nested object array

我有一个这样的数组:

[
   {
        "costs": [{
            "value": "80"
        }],
        "id": 4,
        "name": "Subscription Fee",
        "month": "March"
    },
    [
      {
          "costs": [{
            "value": "200"
          }],
          "id": 2,
          "name": "Tution",
          "month": "March"
      },
      {
          "costs": [{
              "value": "10"
          }],
          "id": 11,
          "name": "DEMO"
      }
   ]
]

我需要汇总成本中的所有值。 我怎样才能做到这一点?

 const data = [ {"costs":[{"value":"80"}],"id":4,"name":"Subscription Fee","month":"March"}, [ {"costs":[{"value":"200"}],"id":2,"name":"Tution","month":"March"}, {"costs":[{"value":"10"}],"id":11,"name":"DEMO"} ] ]; // flatten the arrays to get a list of objects // iterate over this list const res = data.flat().reduce((total, { costs = [] }) => { // add the values of this item's costs with total costs.forEach(({ value = 0 }) => total += +value); return total; }, 0); console.log(res);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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