【问题标题】:JS: dot notation to nested objectJS:嵌套对象的点表示法
【发布时间】:2018-09-25 09:23:50
【问题描述】:

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

这个数组:

["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 中使用它,我可以在其中填充嵌套的 mongoose 文档。然后填充数组传递给我的快速路线中的“.populate(...)”函数

例如:

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

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

根据我的调查,我找到了这个遮阳篷: How transform string dot notation to nested object? 但我不确定如何修改它以达到我的目标。

【问题讨论】:

    标签: javascript mongoose notation


    【解决方案1】:

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

    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; }

    【讨论】:

    • 太棒了!非常感谢!
    【解决方案2】:

    你可以这样做。

    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);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-06
      • 1970-01-01
      • 2015-09-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多