0

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.

1
  • Sorry you're right I need to edit my comment to use {} to show i want hashes not arrays - thank you for pointing that out. Sorry i'm new to all this. Commented Feb 6, 2018 at 10:55

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you i'll take a look at it - unfortunately this is just the first step, as I know later on i'll have more NNID's under the CCIDs....and will have to form trios of those...but this could be a good place to start!
In case it's needed here, prior to 2.3 you could chain .try(:[], :key) as a substitute for :dig. Not pretty, but works to the same goal.
try only works in rails though mind you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.