Reputation: 17332
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"
}
]
}
]
}
Upvotes: 1
Views: 342
Reputation: 1
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);
Upvotes: 2