在Ruby中转换对象数组

时间:2015-05-12 19:52:35

标签: arrays ruby json

我为每个网站的流量提供了一个JSON,包含3个日期。

我想在“Date”上将这三个对象合并在一起。示例如下。

我正在使用Ruby。最简单的方法是什么?

启动JSON:

 [  
   {  
      "Google":[  
         {  
            "Date":"2015-01-01",
            "Value":100
         },
         {  
            "Date":"2015-02-01",
            "Value":200
         },
         {  
            "Date":"2015-03-01",
            "Value":300
         }
      ]
   },
   {  
      "Yahoo":[  
         {  
            "Date":"2015-01-01",
            "Value":1200
         },
         {  
            "Date":"2015-02-01",
            "Value":1300
         },
         {  
            "Date":"2015-03-01",
            "Value":1400
         }
      ]
   },
   {  
      "Bing":[  
         {  
            "Date":"2015-01-01",
            "Value":500
         },
         {  
            "Date":"2015-02-01",
            "Value":600
         },
         {  
            "Date":"2015-03-01",
            "Value":700
         }
      ]
   }
]

结束JSON:

[
  {  
    "Date":"2015-01-01",
    "Google":100,
    "Yahoo":1200,
    "Bing":500
  },
  {  
    "Date":"2015-01-02",
    "Google":200,
    "Yahoo":1200,
    "Bing":600
  },
  {  
    "Date":"2015-01-03",
    "Google":300,
    "Yahoo":1400,
    "Bing":700
  }
]

2 个答案:

答案 0 :(得分:5)

public static void main(String[] args) {
    int n = 5;

    for (int i = 1; i <= n ; i++) {
        System.out.print(fibonacci(i) + " ");
    }
}

public static int fibonacci(int n) {
    if(n == 0) {
       return 0;
    } else if(n == 1) {
       return 1;
    } else {
       return fibonacci(n - 1) + fibonacci(n - 2);
    }
}

为您提供日期为键的哈希值。这可以通过以下方式转换为数组:

result = array.inject({}) do | a, e | 
  site, data = e.first
  data.each do | x | 
    a[x[:Date]] ||= {}
    a[x[:Date]][site] = x[:Value]
  end
  a
end

答案 1 :(得分:0)

假设这个结构正是可行的,那么

results = [] 

your_array[0]['Google'].each_with_index do |item, index|
  date = item['Date']

  provider_values = your_array.inject({}) do |memo, current|
    provider = current.keys[0]
    value = current[provider][index]['Value']

    memo[provider] = value
    memo
  end 
  results.push({'Date' => date}.merge(provider_values))
end

我目前在Windows上,所以我无法100%确定正确性,但修复任何语法错误应该很容易。