嵌套JSON值的总和

时间:2015-11-19 17:23:47

标签: javascript json

我试图从服务器返回的以下一组JSON数据中获取不同状态值的总和。当值没有嵌套时,我的javascript工作正常但不幸的是我需要的数据嵌套在每个对象中。

从下面的代码我试图在警报中返回2的值(两个对象的值为"联系"用"加权"为1)。

使用" status.Status"和" status.Weighting"获取数据不会按预期工作。非常感谢我出错的地方

function showAlert() {
    var requests = 
   [ {          "contactNumber": "098989 258855",
                "createdDate": 1443861343172,
                "firstName": "Ralph",
                "notes": "First time buyer",
                "status": {
                    "Id": 1,
                    "Status": "Referred",
                    "Weighting": "2"
                },
                "surname": "Green",
                "title": "Mr",
                "updatedDate": 1443861343172
            },
     {          "contactNumber": "9999999999",
                "createdDate": 1444728401230,
                "firstName": "Sean",
                "notes": "Landlord",
                "status": {
                    "Id": 5,
                    "Status": "Application made",
                    "Weighting": "5"
                },
                "surname": "Jackson",
                "title": "Mr",
                "updatedDate": 1444728401230
            },
      {        "contactNumber": "9999999999",
                "createdDate": 1444728476347,
                "firstName": "Sam",
                "notes": "Remortgage",
                "status": {
                    "Id": 2,
                    "Status": "Contacted",
                     "Weighting": "1"
                },
                "surname": "Jenkins",
                "title": "Miss",
                "updatedDate": 1444728476347
             },
      {             "contactNumber": "9999999999",
                    "createdDate": 1444728476347,
                    "firstName": "Grace",
                    "notes": "Remortgage",
                    "status": {
                        "Id": 2,
                        "Status": "Contacted",
                        "Weighting": "1"
                    },
                    "surname": "Jones",
                    "title": "Miss",
                    "updatedDate": 1444728476347
                },
    ];
var sumByKey = function (array, keyField, keyValue, valueField) {
    var sum = 0;
    for (var i = 0, len = array.length; i < len; i++)
        if (array[i][keyField] == keyValue)
            sum += parseFloat(array[i][valueField])
    return sum;
}
alert(sumByKey(requests, "status.Status", "Contacted", "status.Weighting"));}

2 个答案:

答案 0 :(得分:2)

你可以做这样的事情仍然使用点符号。这是一个有效的jsfiddle

var sumByKey = function (array, keyField, keyValue, valueField) {
    var sum = 0;
    var keyFieldSplits = keyField.split(".");
    var valueFieldSplits = valueField.split(".");

    array.forEach(function(value){
        var start = value;
        keyFieldSplits.forEach(function(key){
            start = start[key];
        });

        if(start == keyValue) {
            start = value;
            valueFieldSplits.forEach(function(key){
                start = start[key];
            });
            sum += parseInt(start, 10);
        }
    });

    return sum;
}

alert(sumByKey(requests, "status.Status", "Contacted", "status.Weighting"));

答案 1 :(得分:0)

您必须执行以下操作,拆分外部和内部对象键值:

var sumByKey = function (array, outerKeyField, innerKeyField, keyValue, outerValueField, innerValueField) {
    var sum = 0;
    for (var i = 0, len = array.length; i < len; i++)
        if (array[i][outerKeyField][innerKeyField] == keyValue)
            sum += parseFloat(array[i][outerValueField][innerValueField])
    return sum;
}

然后适当地传递属性:

alert(sumByKey(requests, "status", "Status", "Contacted", "status", "Weighting"));}

或者,只要检测到带点符号的键,就必须为函数添加一些字符串解析,并相应地更改逻辑。

这样的事情应该有效:

var sumByKey = function(array, keyField, keyValue, valueField) {
  var sum = 0;
  var thisKey = "";
  var thisValue = "";
  for (var i = 0, len = array.length; i < len; i++) {
    if (keyField.indexOf(".") > -1) {
      var keys = keyField.split(".");
      var obj = array[i][keys[0]];
      for (var j = 1, keyLen = keys.length; j < keyLen; j++) {
        obj = obj[keys[j]];
      }
      thisKey = obj;
    } else {
      thisKey = keyField;
    }
    if (thisKey == keyValue) {
      if (valueField.indexOf(".") > -1) {
        var vals = valueField.split(".");
        obj = array[i][vals[0]];
        for (var j = 1, valLen = vals.length; j < valLen; j++) {
          obj = obj[vals[j]];
        }
        thisValue = obj;
      } else {
        thisValue = array[i][valueField];
      }
      sum += parseFloat(thisValue)
    }
  }
  return sum;
}

var example = [{
  "status": {
    "status": "contacted",
    "weight": 1
  }
}, {
  "status": {
    "status": "contacted",
    "weight": 1
  }
}, {
  "status": {
    "status": "ignored",
    "weight": 1
  }
}];

var sumByKey = function(array, keyField, keyValue, valueField) {
  var sum = 0;
  var thisKey = "";
  var thisValue = "";
  for (var i = 0, len = array.length; i < len; i++) {
    if (keyField.indexOf(".") > -1) {
      var keys = keyField.split(".");
      var obj = array[i][keys[0]];
      for (var j = 1, keyLen = keys.length; j < keyLen; j++) {
        obj = obj[keys[j]];
      }
      thisKey = obj;
    } else {
      thisKey = keyField;
    }
    if (thisKey == keyValue) {
      if (valueField.indexOf(".") > -1) {
        var vals = valueField.split(".");
        obj = array[i][vals[0]];
        for (var j = 1, valLen = vals.length; j < valLen; j++) {
          obj = obj[vals[j]];
        }
        thisValue = obj;
      } else {
        thisValue = array[i][valueField];
      }
      sum += parseFloat(thisValue)
    }
  }
  return sum;
}
alert(sumByKey(example, "status.status", "contacted", "status.weight"));