1
function setup() {
  var names = [];
  var name = {firstname: "", lastname: ""};

  name.firstname = "John";
  name.lastname = "Doe";
  names.push(name);

  name.firstname = "Bill";
  name.lastname = "Smith";
  names.push(name);

  return names;
}

var temp = setup();
print temp[0].firstname;

I can't seem to figure out how to return an array of objects from a function. Any idea where I'm going wrong?

The problem is that the result stored in temp is the following:

 [
   {
     firstname: "Bill",
     lastname: "Smith"
   },
   {
     firstname: "Bill",
     lastname: "Smith"
   }
 ]
Jesse Kernaghan
  • 4,544
  • 2
  • 18
  • 25
roidy
  • 23
  • 1
  • 1
  • 5
  • You are returning an array... that's why temp[0] works. What's the issue? – ryan0319 Jan 19 '16 at 20:33
  • What makes you think something is wrong? What's happening? – aw04 Jan 19 '16 at 20:34
  • Use `document.write( temp[0].firstname )` – Nikolay Ermakov Jan 19 '16 at 20:34
  • you are pushing a reference to the same object into the `names` array, and overwriting the properties of that object. it will mean you have duplicate entries of bill smith in the output array. – synthet1c Jan 19 '16 at 20:36
  • FYI, aside from the fact that JS doesn't deep copy objects automatically, you can actually shorten your code a good bit by simply using a literal structure. No need for `.push()`. `var names = [{firstname: "john", lastname: "doe"}, {firstname: "bill": lastname: "smith"}];` You can also pass multiple items to `.push()` at once. –  Jan 19 '16 at 20:44

2 Answers2

6

You can't reuse name to push the "second" object because you haven't created a second object, it is the same object. So name.firstname="Bill" is changing the first object not creating a second one.

function setup() {
  var names = [];

  var name = {};
  name.firstname = "John";
  name.lastname = "Doe";
  names.push(name);

  var name2 = {};
  name2.firstname = "Bill";
  name2.lastname = "Smith";
  names.push(name2);

  return names;
}

var temp = setup();
alert(temp[0].firstname); // Alerts "John"
Robert McKee
  • 21,305
  • 1
  • 43
  • 57
5

There are 2 problems with your code.

  1. To paint in console, you need to use console.log(temp[0].firstname) in place of print

  2. You have a name object and you are updating it only. And as objects are passed by reference, both the instances at index 0 and index 1 are updated and have same value.

You need to update your code to following

function setup() {
      var names = [];
      var n1 = {};
    
      n1.firstname = "John";
      n1.lastname = "Doe";
      names.push(n1);
    
      var n2 = {};
      n2.firstname = "Bill";
      n2.lastname = "Smith";
      names.push(n2);
    
      return names;
    }
    
    var temp = setup();
    console.log(temp[0].firstname);
Nikhil Aggarwal
  • 28,197
  • 4
  • 43
  • 59