nav function
Access a nested object in root by item sequence.
Implementation
dynamic nav(dynamic root, List items, {bool nullIfAbsent = false}) {
if (root == null) return null;
try {
dynamic current = root;
for (final k in items) {
if (current is JsonMap) {
current = current[k];
} else if (current is List) {
if (k is int && k < 0) {
current = current.last;
} else if (k is int && k < current.length) {
current = current[k];
} else {
throw Exception('Invalid index $k for list');
}
} else {
throw Exception('Invalid navigation at key $k on $current');
}
}
return current;
} catch (e) {
if (nullIfAbsent) return null;
throw Exception(
'Unable to find using path $items on ${json.encode(root)}, exception: $e',
);
}
}