From 69c582eb72c19e8461b43df3f83ca92fdf945816 Mon Sep 17 00:00:00 2001 From: Janine Weber Date: Wed, 17 Apr 2024 09:55:15 +0200 Subject: [PATCH] add general utility functions for objects - objectValueAtPath and objectHasAtPath --- util/object-utilities.libsonnet | 35 +++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 util/object-utilities.libsonnet 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), + }, +}