diff --git a/util/object-utilities.libsonnet b/util/object-utilities.libsonnet new file mode 100644 index 0000000..97858ae --- /dev/null +++ b/util/object-utilities.libsonnet @@ -0,0 +1,35 @@ +local objectHasAtPath(obj, path) = + if std.isObject(obj) == false || std.isArray(path) == false || std.length(path) <= 0 then + false + else if std.length(path) == 1 then + std.objectHas(obj, path[0]) + else + if !std.objectHas(obj, path[0]) then + true + else + objectHasAtPath(obj[path[0]], path[1:]) tailstrict; + +local objectValueAtPath(obj, path, default=null) = + if std.isObject(obj) == false || std.isArray(path) == false || std.length(path) <= 0 then + default + else if std.length(path) == 1 then + if std.objectHas(obj, path[0]) then + obj[path[0]] + else + default + else + if !std.objectHas(obj, path[0]) then + default + else + objectValueAtPath(obj[path[0]], path[1:], default) tailstrict; +{ + // looks through the nested fields of an object to see if it exists - path indicates nested structure + objectHasAtPath(obj, path):: { + result: objectHasAtPath(obj, path), + }, + + // similar to objectHasAtPath, but also returns the value if it exists or a default value + objectValueAtPath(obj, path, default=null):: { + result: objectValueAtPath(obj, path, default), + }, +}