headers 的数组数组到散列数组(然后是 JSON)
Array of arrays with headers to array of hashes(and then JSON)
如何将数组数组(CSV-liks 和 headers)转换为哈希数组?
headers = [['foo', 'bar', 'baz']]
data = [[1,2,3], [4,5,6], [7,8,9]...]
arr_of_arrs = headers + data
arr_of_arrs_to_structured_hash
预期输出类似于
[
{foo: 1, bar: 2, baz: 3}
{foo: 4, bar: 5, baz: 6}
{foo: 7, bar: 8, baz: 9}
]
编辑:抱歉,我刚刚意识到我的输出不清楚。
基本上,数据数组就像 CSV 中的行一样(除了我的数据不是来自 CSV)
headers = [['foo', 'bar', 'baz']]
data = [[1,2,3], [2,3,4]]
data.map(&headers.first.method(:zip)).map(&:to_h)
#⇒ [
# [0] {
# "foo" => 1
# "bar" => 2,
# "baz" => 3,
# },
# [1] {
# "foo" => 2
# "bar" => 3,
# "baz" => 4,
# }
# ]
如何将数组数组(CSV-liks 和 headers)转换为哈希数组?
headers = [['foo', 'bar', 'baz']]
data = [[1,2,3], [4,5,6], [7,8,9]...]
arr_of_arrs = headers + data
arr_of_arrs_to_structured_hash
预期输出类似于
[
{foo: 1, bar: 2, baz: 3}
{foo: 4, bar: 5, baz: 6}
{foo: 7, bar: 8, baz: 9}
]
编辑:抱歉,我刚刚意识到我的输出不清楚。 基本上,数据数组就像 CSV 中的行一样(除了我的数据不是来自 CSV)
headers = [['foo', 'bar', 'baz']]
data = [[1,2,3], [2,3,4]]
data.map(&headers.first.method(:zip)).map(&:to_h)
#⇒ [
# [0] {
# "foo" => 1
# "bar" => 2,
# "baz" => 3,
# },
# [1] {
# "foo" => 2
# "bar" => 3,
# "baz" => 4,
# }
# ]