Skip to content

Latest commit

 

History

History
54 lines (48 loc) · 1.61 KB

deepGet.md

File metadata and controls

54 lines (48 loc) · 1.61 KB
title tags author_title author_url author_image_url description image
deepGet
object
intermediate
Deepak Vishwakarma
Implementation of "deepGet" in typescript, javascript and deno.

TS JS Deno

Returns the target value in a nested JSON object, based on the keys array.

Compare the keys you want in the nested JSON object as an Array. Use Array.prototype.reduce() to get value from nested JSON object one by one. If the key exists in object, return target value, otherwise, return null.

// Guard
function isString<T = any>(str: string | T): str is string {
  return typeof str === "string";
}

const deepGet = (
  obj: any,
  keys: string | (string | number)[],
  delimiter = "."
) => {
  if (isString(keys)) {
    keys = keys.split(delimiter);
  }
  return keys.reduce((xs, x) => (xs && xs[x] ? xs[x] : null), obj);
};
let index = 2;
const data = {
  foo: {
    foz: [1, 2, 3],
    bar: {
      baz: ["a", "b", "c"],
    },
  },
};
deepGet(data, ["foo", "foz", index]); // 3
deepGet(data, ["foo", "bar", "baz", 8, "foz"]); //undefined
deepGet(data, "foo.foz.2"); // 3
deepGet(data, "foo->foz->2", null, "->"); //3
deepGet(data, "foo.bar.baz.8.foz", null); //null