0

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"
1
  • 2
    data = [ { name: "john" } ] Commented Jan 13, 2018 at 7:07

3 Answers 3

2

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";
Sign up to request clarification or add additional context in comments.

Comments

2

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)

Comments

0

That would be

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.