I made an Array of objects named features
. And then I am trying to copy in variable new_array.
var features = mapport.panels.info.current.features();
console.log(typeof features);
new_array = features.slice(0); //new_array is copy of this
And with another method as well like this
var new_array = $.map(features, function (obj) {
return $.extend({}, obj);
});
After this I compare new_array with a array and I delete entries which are not common So after comparison I do like
delete new_array[i].attributes.fields[f_index]
No issue is after deleting specific index values from new_array, it deleting from features
as well.
How to prevent this ?
Example to demonstrate:
var features = [{
attributes: {
fields: ["feat1", "feat2"]
}
}, {
attributes: {
fields: ["feat3", "feat4"]
}
}]
console.log(typeof features);
// This one works!
var new_array0 = $.map(features, function(obj) {
return $.extend(true, {}, obj); // deep clone
});
delete new_array0[1].attributes.fields[0]
document.write(JSON.stringify(new_array0)+'<br>'+JSON.stringify(features)+'<hr>')
// these make shallow copies
var new_array = features.slice(0); //new_array is copy of this
delete new_array[1].attributes.fields[0]
document.write(JSON.stringify(new_array)+'<br>'+JSON.stringify(features)+'<hr>')
var new_array1 = $.map(features, function(obj) {
return $.extend({}, obj);
});
delete new_array1[1].attributes.fields[0]
document.write(JSON.stringify(new_array1)+'<br>'+JSON.stringify(features))
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>