挑选一个JSON对象来创建多个数组

Cherry-picking one JSON object to create multiple arrays

本文关键字:创建 数组 对象 一个 挑选 JSON      更新时间:2023-09-26

我有一个JSON数组,其中包含30个对象(包括今天在内的过去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循环为每个新的数组,但我怀疑有一个更聪明的方法吗?

选项1:Array.prototype.map()

您可以尝试新的javascript Array.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);
});

看这里两个选项的比较

如果您希望进一步消除重复,这里有一个coffeescript解决方案,使用更短的变量名来简化可读性(参见此链接获取等效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]}