Partial implementation for Optional Chaining in ES5
var chain: (sourceObject: object, propertyString: string, defaultValue: any) => any
npm i @hspkg/chain -S
var chain = require('@hspkg/chain');
var testObj = {
code: 200,
data: {
list: [
{ id: 1, name: 'name1' },
{ id: 2, name: 'name2' }
],
page: {
current: 1,
total: 200
}
}
};
// testObj?.code
console.log(chain(testObj, '.code')); // 200
// testObj?.data?.page?.current
console.log(chain(testObj, '.data.page.current')); // 1
// testObj?.data?.list?.[0]?.id
console.log(chain(testObj, '.data.list[0].id')); // 1
// testObj?.wrong?.path
console.log(chain(testObj, '.wrong.path')); // undefined
// testObj?.wrong?.path || 666
console.log(chain(testObj, '.wrong.path', 666)); // 666
MIT