相当于 "SELECT SUM(x)" 在 Javascript 中对 JSON 的查询

Equivalent to "SELECT SUM(x)" query on JSON in Javascript

我有一个 JSON 格式,格式如下:

var myJSON = 
{
  [
    {"project":"4","value":"5"},
    {"project":"2","value":"3"},
    {"project":"4","value":"5"},
    {"project":"4","value":"4"},
    {"project":"1","value":"8"},
  ]
}

我想做一个类似 SELECT SUM(value) WHERE Project = 4 的查询。我怎样才能在 Javascript 中进行这样的查询?我检查了 JSON 路径,但找不到进行此类查询的方法。

一个带有条件的简单 for 完成工作:

var sum = 0;
for(var i in myJSON) { 
    if(myJSON[i].project == 4)
        sum += parseInt(myJSON[i].value);
}

您的 json 数据看起来不正确。可能你需要把它改成

var myJSON = 
{
  data: [
    {"project":"4","value":"5"},
    {"project":"2","value":"3"},
    {"project":"4","value":"5"},
    {"project":"4","value":"4"},
    {"project":"1","value":"8"},
  ]
}

然后总和将如下所示:

var myJSON = 
{
  data: [
    {"project":"4","value":"5"},
    {"project":"2","value":"3"},
    {"project":"4","value":"5"},
    {"project":"4","value":"4"},
    {"project":"1","value":"8"},
  ]
}

var sum = 0;
for(var i = 0; i< myJSON.data.length; i++)  {
  var project = myJSON.data[i];
  if (project.project === "4"){
    sum += parseInt(project.value, 10);
  }
}

这不是有效的 json,请先更正。如果你json是这样的:

var myJSON = 
{
  "data":[
    {"project":"4","value":"5"},
    {"project":"2","value":"3"},
    {"project":"4","value":"5"},
    {"project":"4","value":"4"},
    {"project":"1","value":"8"}
  ]
}

然后使用这个函数求和:

getSum(key){
    let sum = 0;
    myJSON.data.forEach(i=>{
       if(i.project == key){
          sum+= parseFloat(i.value);
       }
    })
  return sum;
}

var JSON = {
  data: [
    {"project":"4","value":"5"},
    {"project":"2","value":"3"},
    {"project":"4","value":"5"},
    {"project":"4","value":"4"},
    {"project":"1","value":"8"},
  ]
}

var sum = 0;
JSON.data.forEach(function(val){
    sum += val.project==="4"? 
            parseInt(val.value, 10): 0;
});
    
console.log(sum);

var sum = jsonPath(myjsonobj, "$.data[?(@.project=='4')].value").reduce(function(pv, cv){
   return parseInt(cv) + parseInt(pv);
});

一些解释:

$.data[?(@.project=='4')].value- 给出一个仅包含 project == "4"

值的数组

reduce(...) - 对数组的所有元素执行一个函数(参见 ECMAScript 文档)

pv, cv - 数组元素的函数调用的先前值和当前值。以前的值是(在此解决方案中)到目前为止的总和,当前值是当前数组元素(作为字符串,因为它在您的数据中)。因此,对于每个数组元素,它的整数值被添加到 "previous" 值,最后由 reduce().

返回