Let's imagine we have an array of objects,
var data = [{
"sss": "sssssss",
"yyy": "ssdsdsds",
"www": "1212121",
"Group": "Mango"
}, {
"sss": "sssssss",
"yyy": "ssdsdsds",
"www": "1212121",
"Group": "Mango"
}]
The desired final result is:
var newData ={
"Mango" : [
{
"sss": "sssssss",
"yyy": "ssdsdsds",
"www": "1212121"
}, {
"sss": "sssssss",
"yyy": "ssdsdsds",
"www": "1212121"
}
]
}
To achieve this, the following approach was taken:
var newObj = [];
for(var i = 0; i < data.length; i++ ){
if(newObj[data[i].Group] && newObj[data[i].Group].constructor === Array ){
}else{
newObj[data[i].Group] = [];
// ################### PROBLEM ==========
var temp = data[i];
delete temp.Group;
console.log(data[i]);
// ################### ==================
newObj[data[i].Group].push(data[i]); // error: data[i].Group is undefined
}
}
In this code snippet, the intention was to remove the property "Group"
from variable "temp"
However, it seems like the console.log(data[i]);
displays that
the property "Group"
has been removed from
data[i]
(which is the original). How is this possible?
It appears that the variable temp
is referencing the original data[i]
, but this is uncertain.
How does deleting a property from a copied object affect the original one? How can this issue be resolved?