Skip to content

Instantly share code, notes, and snippets.

@OliverMax
Created January 22, 2022 20:12
Show Gist options
  • Save OliverMax/9fdf0f70f99ded43c2147c836a328d0a to your computer and use it in GitHub Desktop.
Save OliverMax/9fdf0f70f99ded43c2147c836a328d0a to your computer and use it in GitHub Desktop.

Revisions

  1. OliverMax created this gist Jan 22, 2022.
    38 changes: 38 additions & 0 deletions get.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,38 @@
    const response1 = {
    data: {
    users: [
    {},
    {
    name: 'Oliver',
    surname: 'Max',
    },
    ],
    },
    };

    const response2 = [
    {
    data: {
    users: [
    {},
    {
    name: 'Oliver',
    surname: 'Max',
    },
    ],
    },
    },
    ];

    const get = (data, path, defaultValue = undefined) => path
    ?.split(/\.|\[|\]|'|"/)
    .filter(Boolean)
    .reduce(
    (acc, key) => (acc = acc?.hasOwnProperty(key)
    ? acc[key]
    : defaultValue),
    data,
    );

    console.log(get(response1, 'data.users[1].name', null));
    console.log(get(response2, '[0]["data"].users[1].surname', null));