【问题标题】:JavaScript - "Querying" an ObjectJavaScript - “查询”一个对象
【发布时间】:2016-01-11 16:19:10
【问题描述】:

我想要一种纯 JavaScript 方式来“查询”一个对象。对象如下所示。

[
    {
        "Name": "testName1",
        "Date : "01/01/2016",
        "Volume1 : 1234
        "Volume2 : 1234
    },
    {
        "Name": "testName1",
        "Date : "01/01/2016",
        "Volume1 : 5678
        "Volume2 : 5678
    },
    {
        "Name": "testName1",
        "Date : "01/02/2016",
        "Volume1 : 1234
        "Volume2 : 1234
    },
    {
        "Name": "testName2",
        "Date : "01/01/2016",
        "Volume1 : 1234
        "Volume2 : 1234
    },
    {
        "Name": "testName2",
        "Date : "01/02/2016",
        "Volume1 : 1234
        "Volume2 : 1234
    }
]

我的目标是能够访问每个卷,但需要针对特定​​名称和日期这样做。换句话说,我想返回带有“testName1”且日期为“01/01/2016”的任何内容的总 Volume1。

我试图通过将值附加到 JavaScript 数组来做到这一点:

var dateArray =[];
var nameArray = [];
for (var i = 0; i < obj.length; i++) {
    if (contains(dateArray,obj[i].date == false) { // contains is a function that checks if an item exists in an array
        dateArray.push(obj[i].date;
    }

}

然后我通过将唯一值附加到名称数组来对名称执行相同的操作。

我可以通过添加:

volume += obj[i][Volume1]

在我的 for 循环中;但是,这并不能区分日期和名称。

我在这里的想法是然后以某种方式循环遍历我的唯一值数组并收集满足某些条件但我无法将其放入代码的值。

我还想知道是否有更简洁的方法来做到这一点。

【问题讨论】:

标签: javascript arrays


【解决方案1】:

首先你的 javascript 和 json 是一团糟。大量缺少引号和不匹配的括号。

var arr = [ /*your array*/ ];
var total = arr
  //filters so only items with .name === "testName1" remain
  .filter(function(x) { return x.name === "testName1"; })
  //filters so only items with .date === "01/01/2016" remain
  //this could be replaced with a more robust date check
  .filter(function(x) { return x.date === "01/01/2016"; })
  //sums up all of the values of Volume1 of the remaining items.
  .reduce(function(prev, curr, index) { return prev + curr.Volume1;});

这些函数调用中的每一个基本上都在执行一个 for 循环,以根据您给它的谓词(谓词是一个返回布尔值的函数)执行特定操作。

例如 filter() 可以替换为类似这样的 for 循环。

var output = [];
for(var x in array) {
  if(predicate(array[x])) {
    output.push(array[x]);
  }
}
return output;

当您使用 for 循环时,有时将您的想法分解为每个循环的单个任务是个好主意。它的效率较低(在执行中),但它可以帮助您将您的想法分解为可管理的块。然后,一旦你真正理解了你的代码,你就可以尝试将它们合并到一个循环中。

【讨论】:

  • 这成功了,我使用了你的建议和我的想法的混合体。完美运行。不知道 .filter 方法。因为这个想法是 json 每天都会改变,所以我首先循环 throw 以找出唯一的日期。然后在应用 .filter 的同时循环遍历这些日期以计算所需的体积并将这些值附加到单独的数组中。我现在可以通过在任一数组上使用相同的索引来匹配日期和音量。我可能会尝试将两者组合成一个 key:value 数组。再次感谢,这真的帮助我思考代码。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-05-26
  • 1970-01-01
  • 1970-01-01
  • 2016-12-04
  • 2023-03-09
  • 2020-06-06
  • 1970-01-01
相关资源
最近更新 更多