开发者

How do I sum up properties of a JSON object in coffescript?

I have an object that looks like this one:

object =
  title : 'an object'
  properties :
    attribute1 :
      random_number: 2
      attribute_values:
        a: 10
        b: 'irrelevant'
    attribute2 :
      random_number: 4
      attribute_values:
        a: 15
        b: 'irrelevant'
   some_random_stuff: 'random stuff'

I want to extract the sum of the 'a' values on attribute1 and attribute2.

What wo开发者_高级运维uld be the best way to do this in Coffeescript?

(I have already found one way to do it but that just looks like Java-translated-to-coffee and I was hoping for a more elegant solution.)


Here is what I came up with (edited to be more generic based on comment):

sum_attributes = (x) =>
  sum = 0
  for name, value of object.properties 
    sum += value.attribute_values[x]
  sum

alert sum_attributes('a') # 25
alert sum_attributes('b') # 0irrelevantirrelevant

So, that does what you want... but it probably doesn't do exactly what you want with strings. You might want to pass in the accumulator seed, like sum_attributes 0, 'a' and sum_attributes '', 'b'


Brian's answer is good. But if you wanted to bring in a functional programming library like Underscore.js, you could write a more succinct version:

sum = (arr) -> _.reduce arr, ((memo, num) -> memo + num), 0
sum _.pluck(object.properties, 'a')


total = (attr.attribute_values.a for key, attr of obj.properties).reduce (a,b) -> a+b

or

sum = (arr) -> arr.reduce((a, b) -> a+b)
total = sum (attr.attribute_values.a for k, attr of obj.properties)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜