1

i want to create an object dynamically of the form - {"abc": [x1,x2], "efg": [x3, x4, x1]} The following code is not working.. what's the problem here ?

var catCmp = {};
var x1="abc";
var x2="efg";

var y1="x1";
var y2="x2";
var y3="x3";
var y4="x4";

if (typeof catCmp[x1] === 'undefined') {
    catCmp[x1] = [];
}
if (typeof catCmp[x2] === 'undefined') {
    catCmp[x2] = [];
}

catCmp[x1] = catCmp[x1].push(y1);
catCmp[x1] = catCmp[x1].push(y2);
catCmp[x2] = catCmp[x2].push(y3);
catCmp[x2] = catCmp[x2].push(y4);
catCmp[x2] = catCmp[x2].push(y1);

console.log('catCmp :::', catCmp);
2
  • Why are you doing this catCmp[x1] = catCmp[x1].push(y1); instead of catCmp[x1].push(y1); ? Commented Jan 12, 2012 at 7:08
  • thanks for all the pointers, especially "push method returns length of new object".. Commented Jan 12, 2012 at 9:31

4 Answers 4

6

You need not assign back the result of the push operation. You can simply call catCmp[x1].push(y1);

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

2 Comments

not just you need not, actually you should not, because push method returns length of new object.
Yes, you shouldn't. I was just saying it in a nice way! :-)
3

In the line:

catCmp[x1] = catCmp[x1].push(y1); 

the value returned by catCmp[x1].push(y1) is the value of y1. So that is the value assigned to catCmp[x1].

As suggested in other answers, don't do the assignment, just do:

catCmp[x1].push(y1); 

Comments

0
catCmp[x1].push(y1);
catCmp[x1].push(y2);
catCmp[x2].push(y3);
catCmp[x2].push(y4);
catCmp[x2].push(y1);

Comments

0

JavaScript push method returns the new length of the object upon which push method is called.

So, in your case, the statement

catCmp[x1] = catCmp[x1].push(y1);

makes catCmp[x1] = catCmp[x1].length

Not just you need not, you should not assign back the result of push operation. So, just use:

catCmp[x1].push(y1);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.