Search code examples
arraysjsonrubycsvruby-hash

Array of arrays with headers to array of hashes(and then JSON)


How can I convert array of arrays (CSV-liks with headers) to an array of hashes ?

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

expected output be like

[
 {foo: 1, bar: 2, baz: 3}
 {foo: 4, bar: 5, baz: 6}
 {foo: 7, bar: 8, baz: 9}
]

EDIT : sorry I just realized my output wasn't clear. Basically the data ara array of rows just like in CSV (except my data isn't coming from a CSV)


Solution

  • 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,
    #  }
    # ]