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

时间:2013-06-20 20:19:37

标签: javascript arrays json map

我有一个包含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循环执行此操作,但我怀疑这有更聪明的方法吗?

2 个答案:

答案 0 :(得分:1)

选项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);
});

查看here以查看两个选项之间的比较

答案 1 :(得分:1)

如果您希望进一步消除重复,这里是一个coffeescript解决方案,使用较短的变量名称来提高可读性(请参阅this link了解等效的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]}
相关问题