2

I'm trying to push my variables into this object but not sure how todo this the proper way:

The jsonArray if manually inputted looks like so:

jsonArray = {
        "Person 1": ["Address Rd. City", "777 Street Ave. City"],
        "Person 2": ["Address2 Rd. City2", "777 Street Ave. City"]
        }

I have a loop in which I want to push variables into the jsonArray and i'm trying like so:

   var jsonArray = {};    
   for (var i = 0....my loop, etc)...
   jsonArray.push({fullname: [address, destination]});

This doesn't work, jsonArray always shows as {} when i JSON.stringify(jsonArray)

rubberchicken
  • 1,270
  • 2
  • 21
  • 47

2 Answers2

9

jsonArray — despite the misleading name — is actually an object so try instead

 for (...) {
    jsonArray[fullname] = [address, destination]; 
 }
Fabrizio Calderan
  • 120,726
  • 26
  • 164
  • 177
1

push is a method of Array.prototype. So change the first line to

var jsonArray = []; // array literal

Also declare it like

jsonArray = [
   ["Address Rd. City", "777 Street Ave. City"],
   ["Address2 Rd. City2", "777 Street Ave. City"]
]; // you can use indexes to get the elements
Amit Joki
  • 58,320
  • 7
  • 77
  • 95
  • 1
    this is technically correct but you lose the reference between a person and his address and the capability to use the person as an index – Fabrizio Calderan Nov 25 '14 at 15:31