0

我有一个包含 30 个对象的 JSON 数组(包括今天在内的最近 30 天)。每个对象都有以下属性:

{
    "date": "2013-05-20",
    "notCachedRequestsDevelopment": "115482",
    "cachedRequestsDevelopment": "4732914",
    "notCachedBandwidthDevelopment": "15525231867",
    "cachedBandwidthDevelopment": "2571078929",
    "rejectRequestsDevelopment": "44068",
    "rejectBandwidthDevelopment": "23169212",
    "nonCSSCachedRequestsDevelopment": "6789",
    "nonCSSNotCachedRequestsDevelopment": "1440",
    "notCachedRequestsProduction": "9",
    "cachedRequestsProduction": "1089270",
    "notCachedBandwidthProduction": "2186497",
    "cachedBandwidthProduction": "616508357",
    "rejectRequestsProduction": "359",
    "rejectBandwidthProduction": "168977",
    "nonCSSCachedRequestsProduction": "0",
    "CDNCachedRequests": 6062986,
    "CDNNotCachedRequests": "272901.0",
    "CDNRejectRequests": "84764.0",
    "CDNAllBandwidth": 56006050473.574,
    "billingBandwidth": 22525362831.36,
    "billingHits": 6489103
}

我需要使用这个 JSON 并创建一些新的数组。例如:

我需要一个名为的新数组totalBandwidth,它接受每个 JSON 对象并记录以下属性:notCachedBandwidthDevelopment + cachedBandwidthDevelopment + rejectBandwidthDevelopment + notCachedBandwidthProduction + cachedBandwidthProduction + rejectBandwidthProduction

我需要另一个数组,它调用developmentBandwidth并从每个对象中获取以下总和:cachedBandwidthDevelopment + notCachedBandwidthDevelopment

… 等等。

我可以for为每个新数组循环执行此操作,但我怀疑有更聪明的方法吗?

4

2 回答 2

1

如果您希望进一步消除重复,这里有一个咖啡脚本解决方案,使用较短的变量名来简化可读性(请参阅此链接以获取等效的 javascript):

demoFunction = (daysdata) ->
  result = {}
  totalsNeeded = {foo: ['a', 'b'], bar: ['b','c']}
  sumFields = (fields, obj) ->
    sum = (t,s) -> t+obj[s]
    fields.reduce(sum,0)
  buildDaysArray = (fields) ->
    sumFields(fields,data) for data in daysData
  for name, fields of totalsNeeded
    result[name] = buildDaysArray(fields)
  result


day1 = {a: 1, b: 2, c: 3}
day2 = {a: 4, b: 5, c: 6}
alert(JSON.stringify(demoFunction([day1, day2]))) # => {"foo":[3,9],"bar":[5,11]}
于 2013-06-20T22:02:18.683 回答
1

选项 1:Array.prototype.map()

您可以尝试新的 javascriptArray.prototype.map()数组函数。在您的情况下,您可能需要以下内容:

var developmentBandwidth = origArray.map(function(obj) {
  return parseInt(obj.cachedBandwidthDevelopment) + parseInt(obj.notCachedBandwidthDevelopment);
});

developmentBandwidth将是一个数字数组。

请注意,这仅在 ECMAScript 5 中实现,并且仅在现代浏览器中可用。查看 MDN:https ://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

它们提供了兼容功能,允许您在旧版浏览器上使用该功能。


选项 2:jQuery.map()

看起来 jQuery 库提供了类似的功能。上面的相同示例可以通过以下方式实现:

var developmentBandwidth = $.map(origArray, function(obj, index) {
  return parseInt(obj.cachedBandwidthDevelopment) + parseInt(obj.notCachedBandwidthDevelopment);
});

在此处查看两个选项之间的比较

于 2013-06-20T20:24:18.607 回答