巧妙地添加嵌套属性的方法?

时间:2017-12-05 21:04:10

标签: javascript ecmascript-6

const data = { 
  "orders" : [ 
    { "items" : {"count":3} },  
    { "items" : {"count":1} },  
    { "items" : {"count":2} } 
  ]
}
let total = 0
data.orders.map((order) => order.items.map((item) => (total += item.count)))
console.log(total)

有没有更聪明的方法,我可以说console.log(someoperation(data))

3 个答案:

答案 0 :(得分:4)

您的工作原理,但您也可以使用数组.reduce方法:

const data = { 
  "orders" : [ 
    { "items" : {"count":3} },  
    { "items" : {"count":1} },  
    { "items" : {"count":2} } 
  ]
}

const total = data.orders.reduce((cnt, item) => { return cnt+item.items.count; }, 0)

console.log(total)

编辑:

此外,如果你有lodash,这更容易:

const total = _.sumBy(data.orders, x => x.items.count); // evaluates to 6

答案 1 :(得分:2)

您可以使用嵌套的destructuring assignment作为计数值。

var data = { orders: [{ items: { count: 3 } }, { items: { count: 1 } }, { items: { count: 2 } }] },
    total = data.orders.reduce((s, { items: { count } }) => s + count, 0);

console.log(total);

使用对象进行单个调用的函数

const getCount = ({ orders }) => orders.reduce((s, { items: { count } }) => s + count, 0);

var data = { orders: [{ items: { count: 3 } }, { items: { count: 1 } }, { items: { count: 2 } }] };

console.log(getCount(data));

答案 2 :(得分:0)

将它包装在带有params的函数中:

function getTotal(startVal) {
  var total = startVal;
  data.orders.map((order) => order.items.map((item) => (total += item.count)))  
  const data = { 
    "orders" : [ 
      { "items" : {"count":3} },  
      { "items" : {"count":1} },  
      { "items" : {"count":2} } 
    ]
  }
  return total;
}

console.log(getTotals(0));