【发布时间】:2018-12-18 07:36:07
【问题描述】:
我有一个字符串,它是嵌套 JavaScript 对象中值的路径,例如:
users.userA.credentials.name
我想将此字符串拆分为其元素,然后创建一个包含所有“子路径”的数组,如下所示:
["users", "users.userA", "users.userA.credentials"]
目前我正在通过以下方式解决此问题:
const path = "users.userA.credentials.name"
const currentPath = []
const paths = []
for (const item of path.split('.')) {
currentPath.push(item)
paths.push([...currentPath])
}
它工作正常,但我想知道,是否有更实用的方法(使用map()、filter()、reduce() 或一些lodash/ramda 函数来实现相同的结果。
【问题讨论】:
-
你也要
users.userA.credentials.name作为第四项吗? -
'users.userA.credentials.name'.split('.').map((item,index,all)=>all.slice(0,index+1).join('.')) -
const paths = inits("users.userA.credentials.name".split("."));。你如何实现inits(使用循环、映射、归约等)并不重要。
标签: javascript functional-programming lodash