ceth
ceth

Reputation: 45295

Array of objects - has no method 'push'

I have a code which looks like:

var result = {};

for (var i = 0; i < questions.length; i++)
{
  if(result.hasOwnProperty(questions[i].group)) {
    var questionsInGroup = result[questions[i].group];
    log.debug(typeof questionsInGroup);
    result[questions[i].group] = questionsInGroup.push(questions[i]);
} else {
    result[questions[i].group] = new Array(questions[i]);
}

Here I am trying to create an Associative Array where the keys are strings, and values are arrays of objects.

When I launch this code I get error:

result[questions[i].group] = questionsInGroup.push(questions[i]);
                                              ^
TypeError: Object 2 has no method 'push'

And debug message looks like:

debug: [node/server.js] number

Why the 'questionsInGroup' is a number if I have created it as Array:

result[questions[i].group] = new Array(questions[i]);

Upvotes: 0

Views: 79

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074038

push returns the new length of the array, not the array, so this line:

result[questions[i].group] = questionsInGroup.push(questions[i]);

...overwrites your reference to the array with a number. Simply remove the assignment.


Side note: It's generally best to avoid the Array constructor entirely (use [] instead), and it's always best to avoid it if you're calling it with just one argument. If you give the Array constructor a single argument that's a number, you'll get back an empty array with its length set to that number; but if you call it with any other type of argument, you get back an array with length of 1 containing that argument.

Example:

var a;

a = new Array(2);
display(a.join(", ") + " (" + a.length + ")");

a = new Array("2");
display(a.join(", ") + " (" + a.length + ")");

function display(msg) {
  var p = document.createElement("p");
  p.innerHTML = String(msg);
  document.body.appendChild(p);
}

For that reason, I'd replace:

result[questions[i].group] = new Array(questions[i]);

with

result[questions[i].group] = [questions[i]];

Upvotes: 4

Related Questions