gpt4 book ai didi

JavaScript - "Querying"一个对象

转载 作者:行者123 更新时间:2023-11-30 16:21:09 25 4
gpt4 key购买 nike

我想要一种纯 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 和 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 循环,以根据您给它的谓词执行特定的操作(谓词是一个返回 bool 值的函数)。

例如 filter() 可以替换为如下所示的 for 循环。

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

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

关于JavaScript - "Querying"一个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34726288/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com