What is the best way to update an array of objects with new data?
I'm currently trying to update an array of objects using splice. However, when the below code is executed I get an error saying: "TypeError: Cannot add property 2, object is not extensible".
I'm following the Mozilla documentation for 'splice' and I'm 99% sure I'm doing that part right. The problem seems to be coming from the fact that I'm working with objects. Should I be doing things a different way or following different documentation?
//console.log(designs)
//output:
// (2) [{...}, {...}]
const file = "file-name-example"
let temp = designs.splice(currentIndex, 0, {
image: file,
positions: [0,0,1]
})
The issue is that you are trying to modify an array that has been frozen/sealed (via Object.freeze or Object.seal). Therefore, when the splice method tries to add another property named 3, it cannot as the object has been locked off from modifications. You need to remove the locking code to be able to modify your array again.
Reproduction:
const names = ["Joe", "Jon"];
Object.seal(names);
names.splice(1, 0, "Ben"); // Uncaught TypeError: Cannot add property 2, object is not extensible
const names2 = [...names];
Object.freeze(names);
names.splice(1, 0, "Ben"); // Uncaught TypeError: Cannot add property 2, object is not extensible