2020-07-22
描述
根据给定的多个选择器,从一个对象中获取一组与之匹配的属性值。
提示
- 使用
Array.prototype.map()
迭代每一个选择器 - 使用
String.prototype.replace()
将方括号替换为点 - 使用
String.prototype.split('.')
将每一个选择器都进行分割 - 使用
Array.prototype.filter()
移除空值 - 使用
Array.prototype.reduce()
逐层获取指定的对象值
代码
const get = (from, ...selectors) => [...selectors].map(s => s .replace(/\[([^\[\]]*)\]/g, '.$1.') .split('.') .filter(t => t !== '') .reduce((prev, cur) => prev && prev[cur], from) );
示例
获取指定的属性值:
const obj = { selector: { to: { val: 'val to select' } }, target: [1, 2, { a: 'test' }] }; get(obj, 'selector.to.val', 'target[0]', 'target[2].a'); // ["val to select", 1, "test"]
欢迎来到这里!
我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。
注册 关于