MongoDB
 sql >> Datenbank >  >> NoSQL >> MongoDB

MongoDB/Meteor:Fügen Sie jedem Array-Element eine eindeutige ID hinzu

Dies sollte das Objekt durchlaufen

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

Nutzung

addId(yourObject);