MongoDB / Meteor:为每个数组元素添加唯一ID

时间:2016-01-09 06:16:59

标签: javascript arrays mongodb meteor

如何为此结构中的每个数组元素添加唯一ID?元素的数量是可变的,所以我需要一个动态的解决方案。

{
    "_id" : "wLXDvjDvbsxzfxabR",
    "group" : [
        {
            "title" : "title 1",
            "data" : [
                {
                    "note" : "text"
                }
            ]
        },
        {
            "title" : "title 2",
            "data" : [
                {
                    "note 1" : "text"
                },
                {
                    "note 2" : "text"
                },
                {
                    "note 3" : "text"
                }
            ]
        }
    ]
}

应将ID添加到所有组元素和所有数据元素中。结果应如下所示:

{
    "_id" : "wLXDvjDvbsxzfxabR",
    "group" : [
        {
            "id" : "dfDFSfdsFDSfdsFws",
            "title" : "title 1",
            "data" : [
                {
                    "id" : "efBDEWVvfdvsvsdvs",
                    "note" : "text"
                }
            ]
        },
        {
            "id" : "fdsfsFDSFdsfFdsFd",
            "title" : "title 2",
            "data" : [
                {
                    "id" : "WVvfsvVFSDWVDSVsv",
                    "note 1" : "text"
                },
                {
                    "id" : "qqdWSdksFVfSVSSCD",
                    "note 2" : "text"
                },
                {
                    "id" : "MZgsdgtscdvdsRsds",
                    "note 3" : "text"
                }
            ]
        }
    ]
}

1 个答案:

答案 0 :(得分:2)

这应该遍历对象

function generateId() {
    // you'll have to write this yourself
}

function addId(obj) {
    if (Object.prototype.toString.call(obj).indexOf('Array') >= 0) {
        obj.forEach(function(item) {
            item.id = item.id || generateId();
            addId(item);
        });
    }
    else if (typeof obj == 'object') {
        Object.keys(obj).forEach(function(key) {
            addId(obj[key]);
        });
    }
}

使用

addId(yourObject);