devnext
devnext

Reputation: 902

How to declare object in array variable?

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"

Upvotes: 0

Views: 62

Answers (3)

JohnPan
JohnPan

Reputation: 1210

That would be

let data =[]; data[0] = {"name":"john"}

Upvotes: 0

palaѕн
palaѕн

Reputation: 73906

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)

Upvotes: 2

Nisarg Shah
Nisarg Shah

Reputation: 14541

You would need to declare the first element of the array to be an object, before you can set properties on that object.

One of the ways of doing so would be:

let data = [];
data[0] = {};
data[0].name = "john";

Upvotes: 2

Related Questions