简体   繁体   中英

Ruby - Extract array from nested array of hashes

I'm trying to obtain a hash from the following:

 response: 
 {"result": [
 {
  "LEID": "123",
  "result": [
    {
      "CCID": "456",
      "result": [
        {
          "Amount": 10000,
          "NNID": "789"
        }
      ]
    },
    {
      "CCID": "ABC",
      "result": [
        {
          "Amount": 5000,
          "NNID": "DEF"
        }
      ]
    }
  ]
}
]
}

What i'm trying to do is get the following out:

{"LEID":123,"CCID":456,"NNID":789}

{"LEID":123,"CCID":ABC,"NNID":DEF}

So get a trio of LEID, CCID and NNID

So far what I have is:

  LEID_collection = response['result']
  LEID = LEID_collection.map {|h| h['LEID']}
  LEID = LEID.reduce
  CCID_collection = LEID_collection.reduce
  CCIDs = CCID_collection['result'].map {|h|h['CCID']}
  CCID1 = CCIDs[0]
  CCID2 = CCIDs[1]
  CCIDs = CCID_collection['result']
  test = CCIDs.first.keys.zip(CCIDs.map(&:values).transpose).to_h
  test2 = test['result']
  test3 = test2.flatten
  test4 = test3.map {|h| h['NNID']}
  NNID1 = test4[0]
  NNID2 = test4[1]

  hash1 = Hash["LEID", LEID, "CCID", CCID1, "NNID", NNID1]
  puts "hash 1 :" +  hash1.to_s
  hash2 = Hash["LEID", LEID, "CCID", CCID2, "NNID", NNID2]
  puts "hash 2 :" +  hash2.to_s

This gets what I want but is really not dynamic... are there any better ways?

Sorry for how convoluted this is, i'm just not sure how to explain it any other way. Happy to answer any questions.

If you know that you'll always have this structure and you use ruby >= 2.3.0, then you can use the dig method to shorten things:

collection = response['result'].first
trios = collection['result'].map do |ccid|
  {
    'LEID' => collection['LEID'],
    'CCID' => ccid['CCID'],
    'NNID' => ccid.dig('CCID', 'NNID')
  }
end

Its only a little shorter but hopefully easier to read overall.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM