简体   繁体   中英

MongoDB/Meteor: Add unique ID to every array element

How can I add a unique ID to every array element in this structure? The number of elements are variable, so I need a dynamic solution.

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

The ID should be added to all group-elements and all data element. The result should look like:

{
    "_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"
                }
            ]
        }
    ]
}

This should iterate through the object

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

usage

addId(yourObject);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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