简体   繁体   中英

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

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

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); 
catCmp[x1].push(y1);
catCmp[x1].push(y2);
catCmp[x2].push(y3);
catCmp[x2].push(y4);
catCmp[x2].push(y1);

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM