Safely read a nested value by dot or bracket path with fallback
An order details page reads many fields from a large API response, such as order.customer.address.city or the SKU of the last line item. Some fields are missing on older orders, and a single undefined halfway down the chain crashes the page. The team wants one safe reader that never throws.
Implement readPath(source, path, fallback). It follows path into source and returns the value found there, or fallback when there is no value.
readPath(source, path, fallback?) // => the value at path, or fallback
'items[1].sku' means the keys items, 1, sku. A dot works for indexes too: 'items.1.sku' is the same path.['items', 1, 'sku']. Each element is one key, even if it contains a dot: ['feature.flags', 'beta'].'items[-1]' is the last item. On anything that is not an array, -1 is an ordinary key.'' or []) refers to source itself.null or undefined before the path ends, return fallback. Never throw.undefined, return fallback.null, 0, '', and false.'name.length' works on a string and 'items.length' works on an array.fallback defaults to undefined.const order = {
customer: { name: 'Rhea', address: { city: 'Lisbon', zip: null } },
items: [{ sku: 'MUG-1', qty: 2 }, { sku: 'TEE-4', qty: 1 }],
};
readPath(order, 'customer.address.city'); // => 'Lisbon'
readPath(order, 'items[1].sku'); // => 'TEE-4'
readPath(order, 'items[-1].qty'); // => 1
readPath(order, ['items', 0, 'sku']); // => 'MUG-1'
readPath(order, 'customer.phone.mobile', '-'); // => '-'
readPath(order, 'customer.address.zip', '-'); // => null