Javascript 使用递归将嵌套对象重新格式化为字符串数组
我的目标如下:Javascript 使用递归将嵌套对象重新格式化为字符串数组,javascript,Javascript,我的目标如下: const modules = { celebrity: { actor: { male: 'male', female: 'female' }, director: 'director' }, movie: 'movie', user: 'user' }; 因此,我需要一个字符串数组,如下所示: [ "celebrity/actor
const modules = {
celebrity: {
actor: {
male: 'male',
female: 'female'
},
director: 'director'
},
movie: 'movie',
user: 'user'
};
因此,我需要一个字符串数组,如下所示:
[
"celebrity/actor/male",
"celebrity/actor/female",
"celebrity/director",
"movie",
"user"
]
我创建以下函数:
function getPathsList(node, path = '') {
let pathsList = [];
const childs = Object.entries(node);
for (const child of childs) {
if (typeof child[1] === 'string') {
path += `/${child[1]}`
pathsList.push(path)
} else {
path += `/${child[0]}`
pathsList = [...pathsList, ...getPathsList(child[1], path, pathsList)]
}
}
return pathsList;
}
但我得到了:
[
"/celebrity/actor/male",
"/celebrity/actor/male/female",
"/celebrity/actor/director",
"/celebrity/movie",
"/celebrity/movie/user"
]
我知道path变量应该在某个地方初始化,但我搞不清楚。您可以使用一个appraoch,它在没有路径的情况下工作,但通过迭代嵌套零件对象来组装路径 函数getPathsList(节点){ 常量路径列表=[]; for(对象项(节点)的常量[键,值]){ if(value&&typeof value==='object'){ push(…getPathsList(value).map(p=>`${key}/${p}`) }否则{ 路径列表。按(键); } } 返回路径列表; } 常数模={ 名人:{ 演员:{ 男:"男",, 女:“女” }, 导演:“导演” }, 电影:"电影",, 用户:“用户” }; log(getPathsList(modules))代码>另一种方式,使用:
const modules={名人:{演员:{男:“男”,女:“女”},导演:“导演”},电影:“电影”,用户:“用户”};
函数getPathsList(节点,路径=“”){
返回Object.entries(节点)
.减少(
(res[k,v])=>res.concat(
typeof v==“string”?`${path}${v}`:getPathsList(v,`${path}${k}/`
)
), []);
}
log(getPathsList(modules))代码> 您可以考虑一种“DFS”类算法,从根到叶遍历每个路径。
然后用“/”连接路径
微妙之处:不要将叶子本身放入路径中(例如:否则你会得到电影/电影)
下面是一个使用flatMap的示例
const modules={“名人”:{“演员”:{“男”:“男”,“女”:“女”},“导演”:“导演”},“电影”:“电影”,“用户”:“用户”}
常数展平=x=>{
if(typeof(x)=='string'){return[]]}
//每个节点都有其条目的子节点
//每个节点返回一个路径数组
返回Object.entries(x).flatMap([k,v])=>{
返回展平(v).map(路径=>[k,…路径])
})
}
console.log(展平(模块).map(路径=>path.join('/'))
困难在哪里
const
模块=
{名人:
{演员:{男:男,女:女}
,导演:“导演”
}
,电影:《电影》
,用户:'user'
}
,路径列表=[]
;
函数getPathsList(对象,路径=“”)
{
用于(输入obj)
{
if(typeof(obj[key])==='object')getPathsList(obj[key],path+'/'+key)
else-pathsList.push((路径+'/'+键).substring(1))
}
}
getPathsList(模块)
console.log(路径列表)