obj.prop(path)
ๅฆๆ JavaScript ๅผๆไธๆฏๆด optional chaining (?., ?.[])๏ผๅฐฑๅฏไปฅ็จไธ้ข็็จๅผใ
็ฑๆผไฝฟ็จ mixin ็ๆนๅผ๏ผๆไปฅ็ถๆๅไฝฟ็จ user.prop('info.age')
็ๆนๅผไพ่ฎๅ็ฉไปถๅฑฌๆงๆ๏ผuser
ๆฌ่บซๅทฒ็ถ็ขบๅฎๆฏๅ็ฉไปถ(ไธๆๆฏ null ๆ undefined)๏ผๅ ๆญคๆๅๅจ prop(path)
้ๅ method ๅ
ง้จไธฆๆฒๆๅปๆชขๆฅ this
ๆฏไธๆฏ null ๆ undefinedใ
replit โฉ obj.prop(path)
// โญ mixin for objects
const ObjectTools = {
// obj.prop(path)
prop(path) {
let value = this;
let components = path.split('.');
while (components.length) {
// pull first component
let component = components.shift();
// check if last character === '?'
const isValueOptional = component.slice(-1) === '?';
if (isValueOptional) {
// remove "?"
component = component.slice(0, -1);
// get nested property
value = value[component];
// return early if value is nullish
if (value === null || value === undefined) return undefined;
} else {
// if not optional, get property directly
value = value[component];
}
}
return value;
}
};
// for node.js module
module.exports = objectTools;
๐็ฏไพ๏ผ
"use strict";
const { log } = console;
// โญ mixin for objects
const ObjectTools = require('./ObjectTools.js');
// ---------- main ------------
// test object
const user = {
name: 'Joy',
info: {
address: {
street: '5th Street',
zip: 333,
}
}
};
// โญ apply mixin to `obj`
Object.assign(user, ObjectTools);
// ---------- log ------------
;
[
user.prop("info.address"), // { street: '5th Street', zip: 333 }
user.prop("info.address.street"), // '5th Street'
user.prop("info.address.street.bar"),// undefined
user.prop("info.age"), // undefined
user.prop("info.age?.details"), // undefined
user.prop("bar?.age?.details"), // undefined
// user.prop("bar.age"), // โ TypeError:
// ^^^ <---- Cannot read property 'age' of undefined
user === global.user, // false: `const` doesn't create property of `global`
].forEach(x => log(x));
// user.prop("info.address.street")
// ---------------------------------
// initial states:
//
// โข value = user
// โข components = [ 'info', 'address', 'street' ]
//
// while loop:
// --------------------------------------------------------------------
// length shift() components value
// --------------------------------------------------------------------
// 3 'info' ['address', 'street'] user.info
// 2 'address' ['street'] user.info.address
// 1 'street' [ ] user.info.address.street
// 0 <---- exit while loop โฐโโ return value โโโโฏ
// --------------------------------------------------------------------
eval() โฉ accessing member properties โญ๏ธ
Global object unlike
var
,let
andconst
do not create properties of the global object.
use the concept of mixin.
Last updated