select - 选择对象中的属性值

优质
小牛编辑
123浏览
2023-12-01

从对象中检索出给定选择器指定的一组属性。

对每个选择器使用 Array.map() ,使用 String.split('.') 来分割每个选择器,并使用 Array.reduce() 来获取它所指示的值。

const select = (from, ...selectors) =>
  [...selectors].map(s => s.split('.').reduce((prev, cur) => prev && prev[cur], from));
const obj = { selector: { to: { val: 'val to select' } } };
select(obj, 'selector.to.val'); // ['val to select']
select(obj, 'selector.to.val', 'selector.to'); // ['val to select', { val: 'val to select' }]