findKeyPathValue<V> function

V? findKeyPathValue<V>(
  1. Map? map,
  2. String? keyPath, {
  3. String keyDelimiter = '/',
  4. bool isValidValue(
    1. Object? value
    )?,
})

Finds in map a value that is in key path keyPath

keyDelimiter The key path delimiter. isValidValue validates a matching value.

Implementation

V? findKeyPathValue<V>(Map? map, String? keyPath,
    {String keyDelimiter = '/', bool Function(Object? value)? isValidValue}) {
  if (map == null || map.isEmpty || keyPath == null || keyPath.isEmpty) {
    return null;
  }

  var keys = keyPath.split('/');

  var value = findKeyValue(map, [keys.first], true);
  if (value == null) return null;

  for (var i = 1; i < keys.length; ++i) {
    var k = keys[i];

    if (value is Map) {
      value = findKeyValue(value, [k], true);
      if (value == null) return null;
    } else if (value is List) {
      var idx = parseInt(k);
      if (idx != null) {
        value = value[idx];
      } else {
        return null;
      }
    } else {
      return null;
    }
  }

  if (isValidValue != null) {
    if (isValidValue(value)) {
      return value as V?;
    } else {
      return null;
    }
  } else {
    return value as V?;
  }
}