1

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"
                }
            ]
        }
    ]
}
1
  • have you tried just looping through the group array, assigning id values to each element? Commented Jan 9, 2016 at 6:26

1 Answer 1

2

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);
Sign up to request clarification or add additional context in comments.

2 Comments

absolutely not ... genid is the parameter name within the addId function - you COULD do it without all reference to genid (remove it in the arguments) and use generateId in the addId function - however, I wrote this with flexibility in mind ... I'll rewrite it simpler
There - simpler with less possibility for confusion

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.