user644745
user644745

Reputation: 5723

javascript object key and value as array

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);

Upvotes: 1

Views: 142

Answers (4)

hrishikeshp19
hrishikeshp19

Reputation: 9036

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);

Upvotes: 0

RobG
RobG

Reputation: 147523

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); 

Upvotes: 3

user1046334
user1046334

Reputation:

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

Upvotes: 0

techfoobar
techfoobar

Reputation: 66693

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

Upvotes: 6

Related Questions