Home > Software design >  Extract value from optional nested object
Extract value from optional nested object

Time:04-04

How to extract value with static key (:value) in situation when we have object with one of optional nested objects?

message_obj = {
  'id': 123456,
  'message': {
    'value': 'some value',
  }
}

callback_obj = {
  'id': 234567,
  'callback': {
    'value': 'some value',
  }
}

In this situation, I using next instruction:

some_obj[:message] ? some_obj[:message][:value] : some_obj[:callback][:value]

How to extract value from nested object, then we know list of acceptable objects names (eg. [:message, :callback, :picture, ...]). In parent object exist only one nested object.

CodePudding user response:

I would use Hash#values_at and then pick the value the one hash that was returned:

message
  .values_at(*[:message, :callback, :picture, ...])
  .compact
  .first[:value]

CodePudding user response:

You could use dig

For example:

message_obj = {
  'id': 123456,
  'message': {
    'value': 'some message value',
  }
}

callback_obj = {
  'id': 234567,
  'callback': {
    'value': 'some callback value',
  }
}

objects = [message_obj, callback_obj]

objects.each  do |obj|
    message_value = obj.dig(:message, :value)
    callback_value = obj.dig(:callback, :value)
    puts "found a message value #{message_value}" if message_value
    puts "found a callback value #{callback_value}" if callback_value
end

This would print:

found a message value some message value
found a callback value some callback value

  • Related