从JSON中的数组乘以'Odds`值

时间:2017-04-25 15:54:15

标签: javascript html

我从这个

中获取了一个来自url的json数组
{"soccerodds2017":[
    {"Selections":"Chelsea","Odds":"1.44"},
    {"Selections":"Wolverhampton","Odds":"2.33"},
    {"Selections":"Walsall","Odds":"2.70"}
]}

我想将赔率乘以10 例如:10*1.44*2.33*2.70并得到总数。如何在javascripts中做到这一点?

2 个答案:

答案 0 :(得分:6)

您可以使用reduce()将累加器的初始值设置为10,然后将每个e.Odds值相乘。

var obj = {"soccerodds2017":[{"Selections":"Chelsea","Odds":"1.44"},{"Selections":"Wolverhampton","Odds":"2.33"},{"Selections":"Walsall","Odds":"2.70"}]}

var total = obj.soccerodds2017.reduce(function(r, e) {
  return r * +e.Odds
}, 10)

console.log(total)

答案 1 :(得分:0)

您可以创建一个通用函数来处理乘法处理。



var data = { "soccerodds2017": [
  { "Selections" : "Chelsea",       "Odds": "1.44" },
  { "Selections" : "Wolverhampton", "Odds": "2.33" },
  { "Selections" : "Walsall",       "Odds": "2.70" }
]};

console.log(calculate(data['soccerodds2017'], 'Odds', (x, y) => x * parseFloat(y), 10));

function calculate(data, prop, fn, initVal) {
  return data.reduce((total, value) => fn.call(this, total, value[prop]), initVal || 0);
}

.as-console-wrapper { top: 0; max-height: 100% !important; }




您还可以创建一个计算器类来处理所有样板逻辑。



class Calculator {
  constructor(type = 'float') {
    this.type = type;
  }
  calc(data, prop, op, initVal) {
    initVal = initVal || 0;
    switch (op) {
      case 'add' : return this.__calculate__(data, prop, this.constructor.add, initVal);
      case 'sub' : return this.__calculate__(data, prop, this.constructor.sub, initVal);
      case 'mul' : return this.__calculate__(data, prop, this.constructor.mul, initVal);
      case 'div' : return this.__calculate__(data, prop, this.constructor.div, initVal);
      throw Error('Operation not supported');
    }
  }
  __calculate__(data, prop, fn, initVal) {
    return data.reduce((total, value) => fn.call(this, total, prop ? value[prop] : value), initVal);
  }
}

class IntegerCalculator extends Calculator {
  constructor() {
    super('int')
  }
  static add(x, y)   { return x + parseInt(y, 10); }
  static sub(x, y)   { return x - parseInt(y, 10); }
  static mul(x, y)   { return x * parseInt(y, 10); }
  static div(x, y)   { return x / parseInt(y, 10); }
}

class FloatCalculator extends Calculator {
  constructor() {
    super('float')
  }
  static add(x, y) { return x + parseFloat(y); }
  static sub(x, y) { return x - parseFloat(y); }
  static mul(x, y) { return x * parseFloat(y); }
  static div(x, y) { return x / parseFloat(y); }
}

var floatCalc = new FloatCalculator();
var data = { "soccerodds2017": [
  { "Selections" : "Chelsea",       "Odds": "1.44" },
  { "Selections" : "Wolverhampton", "Odds": "2.33" },
  { "Selections" : "Walsall",       "Odds": "2.70" }
]};

console.log(floatCalc.calc(data['soccerodds2017'], 'Odds', 'mul', 10));

.as-console-wrapper { top: 0; max-height: 100% !important; }