繁体   English   中英

JS:嵌套对象的点符号

[英]JS: dot notation to nested object

我挣扎于这个简单的功能。 我的目标是将点符号字符串解析为嵌套对象。

一个这样的数组:

["image", "groups", "groups.tasks", "groups.image"]

我应该给这个:

[{
        path: "image",
        populate: []
    }, {
        path: "groups",
        populate: [{
                path: "tasks",
                populate: []
            }, {
                path: "image",
                populate: []
            }]
    }]

到目前为止我的代码:

 let populate = []; const query = ["image", "groups", "groups.tasks", "groups.image"]; function parse(str, arr) { let c = str.split("."); let p = c.shift(); console.log(c) let entry = { path: p, populate: [] }; if (c.length > 0) { console.log("Add to '%s'", p, c) parse(c.join("."), entry.populate); } else { arr.push(entry); } } query.forEach(function (str, index) { parse(str, populate); }); console.log(populate)

我得到的只是父数组,没有孩子:

[ { path: 'image', populate: [] },
  { path: 'groups', populate: [] } ]

我想在 RESTful API 中使用它,我可以在其中填充嵌套的猫鼬文档。 然后填充数组将 i 传递给我的快速路由中的“.populate(...)”函数

例如:

GET /api/computer?populate=image,groups,group.tasks

嵌套对象的深度应该没有限制。

通过我的研究,我发现了这个 awnser: 如何将字符串点表示法转换为嵌套对象? 但我不知道如何修改它以达到我的目标。

您可以通过减少拆分的路径字符串来减少数组。

 var array = ["image", "groups", "groups.tasks", "groups.image"], result = array.reduce((r, s) => { s.split('.').reduce((a, path) => { var object = a.find(o => o.path === path); if (!object) { a.push(object = { path, populate: [] }); } return object.populate; }, r); return r; }, []); console.log(result);
 .as-console-wrapper { max-height: 100% !important; top: 0; }

你可以做这样的事情。

 var aa = ["groups","image","groups.tasks", "groups.image" ] var result = []; aa.forEach(element => { if (!result.some(a=> a.path === element) && element.indexOf(".") === -1) { result.push({ path: element, populate: [] }) } else { if (element.indexOf(".") !== -1) { let splittedText = element.split("."); if (result.some(a=> a.path === splittedText[0])) { var index= result.findIndex(a=> a.path === splittedText[0]); result[index].populate.push({ path: splittedText[1], populate: [] }); }else{ result.push({ path: splittedText[0], populate: [{ path: splittedText[1], populate: [] }] }) } } } }); console.log(result);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM