1

I want to create an array like this:

send[1]['conversation_group_id']=1;

But i get an error that cannot set property conversation_group_id of undefined. What am i doing wrong?

Thanks!

5
  • how did you init send? Commented Aug 13, 2017 at 17:07
  • 1
    If you want to add a property to an Object, you need to first create that Object. Here, as the error tells you, send[1] is not an Object, it is not defined. Commented Aug 13, 2017 at 17:07
  • @Sirko send=[]; Commented Aug 13, 2017 at 17:09
  • 1
    You've initialized the array, but not an object. send[1] would have to point to the second element in an array that is an object, but currently it's nothing. If you first did send[1] = {} and then send[1]['conversation_group_id'] = 1 - it would work. Commented Aug 13, 2017 at 17:10
  • 1
    Possible duplicate of Cannot set property '0' of 2D array Commented Aug 13, 2017 at 17:12

2 Answers 2

5

Even though you have initialized send with [], which makes it an array, send[1] will be undefined, you will need to initialize it as an object too before you can set a property inside it. At the moment you are trying to set a property of undefined.

var send = [];
console.log(send[1]);
send[1] = {};
send[1]['conversation_group_id']=1;
console.log(send[1]['conversation_group_id']);

Sign up to request clarification or add additional context in comments.

Comments

1

Your data structure is an array of objects. To initialize it, you can also do it this way.

send = [null, {conversation_group_id: 1}]

Nothing wrong with @Dij's answer, but just though it's worth mentioning an alternative on how to initialize the structure you're looking for.

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.