如何在 Javascript React Native 中获取对象的子值总和?

Tax*_*oul 2 javascript json object ecmascript-6 react-native

这是我的对象:

 var obj = {
  "idtransact1":  {

    "amount": 3000,

  },
  "idtransact2":  {

    "amount": 3000,

  }
}
Run Code Online (Sandbox Code Playgroud)

我正在尝试获取所有金额的总和。我尝试改编这个示例,但由于它不是相同的数据结构,所以我有点迷失。

var array = [{
  "adults": 2,
  "children": 3
}, {
  "adults": 2,
  "children": 1
}];

var val = array.reduce(function(previousValue, currentValue) {
  return {
    adults: previousValue.adults + currentValue.adults,
    children: previousValue.children + currentValue.children
  }
});
console.log(val);  
Run Code Online (Sandbox Code Playgroud)

任何帮助,将不胜感激。

Moh*_*man 5

您可以使用Object.values().reduce()来获得总和:

const data = {
  "idtransact1":  { "amount": 3000 },
  "idtransact2":  { "amount": 3000 }
};

const result = Object.values(data).reduce((r, { amount }) => r + amount, 0);
                   
console.log(result);
Run Code Online (Sandbox Code Playgroud)