A scenario involves an object with incoming data and an array that contains saved data. The goal is to check if the "cnName" from the new data already exists in the "savedData" array. If it does, then the object in "savedData" should be replaced with the new data object. If it does not exist, the new data should be pushed to the "cnData" array in "savedData."
newData = {
"cnGroupName": "cnGroupName1",
"cnData": [{
"cnName": "cn3",
"data": {
"color": "blue",
"size": "42",
"position": "right"
}
}]
}
savedData = [{
"cnGroupName": "cnGroupName1",
"cnData": [{
"cnName": "cn1",
"data": {
"color": "red",
"size": "42",
"position": "right"
}
}, {
"cnName": "cn2",
"data": {
"color": "blue",
"size": "11",
"position": "top"
}
}]
}]
Underscore is being used in this implementation.
if(savedData.length){
_.each(savedData, function(num, i){
if(savedData[i].cnGroupName == newData.cnGroupName ){
_.each(savedData[i].cnData, function(num, x){
if(savedData[i].cnData[x].cnName == newData.cnData[0].cnName){
// Replace the existing object in savedData with newData
savedData[i].cnData[x] = newData.cnData[0]
}else{
// Push the new object to savedData as the cnName does not exist
savedData[i].cnData.push(newData.cnData[0])
}
})
}else{
// Push newData if the cnGroupName from newData is not in savedData
savedData.push(newData)
}
})
}
The issue with this approach is that if the "cnName" does not exist in "savedData," the new data will be pushed multiple times based on the existing objects in "savedData."
Console logs in this plunker demonstrate that the new data is being duplicated.
http://plnkr.co/edit/GkBoe0F65BCEYiFuig57?p=preview
Two questions arise:
- Is there a more efficient method using underscore for this purpose?
- Is there a way to stop _.each() from proceeding to the next iteration?