How do I declare object in an array variable. It shows the below error
"TypeError: Cannot set property 'name' of undefined"
This is the code:
let data = []
data[0].name = "john"
You are getting an error because data is an empty array and hence data array does not have any element at position 0. Hence when you try to access it like data[0] (which you can check in console), you will get undefined. Any trying to set a new name property to undefined gives Cannot set property 'name' of undefined" error. You can fix this issue in many ways, one of the ways is to just push the new object like:
let data = []
data.push({ name : "john"});
console.log(data)
Or, you can also try to declare data[0] to an empty object first, so that you can assign any new property to it after that like:
let data = [];
data[0] = {};
console.log(typeof data[0]); // This is not undefined anymore
data[0].name = "john";
console.log(data)
data = [ { name: "john" } ]