@bitty/get
A really small and type-safe (requires TypeScript >= 4.1.3) function, that gets a nested value from an object using a path string (like "a.b[0].d"
). If value is undefined
or unreachable returns the placeholder instead.
It's approach is based on idx, from Facebook, and an insight from a Vue.js meetup where @IgorHalfeld showed a way to get nested values using eval
.
Install
This library is published in the NPM registry and can be installed using any compatible package manager.
npm install --save @bitty/get
yarn add @bitty/get
Installation from CDN
This module has a UMD bundle available through JSDelivr and Unpkg CDNs.
<script src="https://unpkg.com/@bitty/get"></script>
<script src="https://cdn.jsdelivr.net/npm/@bitty/get"></script>
<script>
console.log(get);
var users = [{ name: 'Carlos Marcos' }];
console.log(get(users, '[0].name', 'Unknown'));
</script>
Usage
Just import get
function and gets a value from object using a path expression.
import get from '@bitty/get';
const name = get(response, 'data.user.name', 'Unknown');
You can use brackets, even on first property.
const title = get(paragraphs, '[0].children[0].textContent');
License
Released under MIT License.