0

I want to define what I understand is an associative array (or maybe an object) such that I have entries like the following: "Bath" = [1,2,5,5,13,21] "London" = [4,7,13,25]

I've tried the following:

var xref = new Object;
xref = [];
obj3 = {
      offices: []
      };
xref.push(obj3);

Then cycling through my data with

xref[name].offices.push(number);

But I get "TypeError: xref[name] is undefined". What am I doing wrong ?

dachi
  • 1,604
  • 11
  • 15
Leamphil
  • 77
  • 1
  • 1
  • 4
  • What is `name` in your example? Also, you should be using an object, not an array. Initializing `xref` with `new Object` and then assigning the value `[]` in the next line is somewhat pointless. I recommend to read [MDN - Working with Objects](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects). – Felix Kling Mar 01 '14 at 20:03
  • `var xref = new Object; xref = [];` is the same as `var xref = new Object(); xref = new Array();`. You can't use named keys in javascript arrays. Remove the `[]` declaration. – h2ooooooo Mar 01 '14 at 20:04

3 Answers3

1

Use an object like you do with obj3:

var xref = {};
xref.obj3 = obj3;
var name = 'obj3';
xref[name].offices.push(number);
GManz
  • 1,548
  • 2
  • 21
  • 42
0
var obj = {
   arr : [],
}

var name = "vinoth";
obj.arr.push(name);
console.log(obj.arr.length);
console.log(obj.arr[0]);

obj.prop = "Vijay";
console.log(obj.prop);

You can use an object literal.

Thalaivar
  • 23,282
  • 5
  • 60
  • 71
0

I realised that all I really wanted was a 2 dimensional array with the first dimension being the key (ie. "BATH", "LONDON") and the second being the list of cross-references (ie. 1,2,5,5,13,21) - so I don't need to understand the Object route yet ! The other suggestions may well work and be "purer" but the 2 dimensional array is easier for my old-fashioned brain to work with.

So I did the following:

var xref = [];
// go through source arrays
for (i = 0; i < offices.length; i++) { 
  for (j = 0; j < offices[i].rel.length; j++) {
     // Check if town already exists, if not create array, then push index
     if (xref[offices[i].rel[j].town] === undefined) {
        xref[offices[i].rel[j].town] = [];
        alert('undefined so created '+offices[i].rel[j].town);
        };
     xref[offices[i].rel[j].town].push(i);    // Add index to town list
     };
  };

I believe from reading other posts that I would have problems if any of the 'offices[i].rel[j].town' were set to undefined but the data doesn't have this possibility.

Now I can access a cross-reference list by doing something like:

townlist = "";
for (i = 0; i < xref["BATH"].length; i++) {
   townlist += offices[xref["BATH"][i]].name+' ';
   };
alert(townlist);
Leamphil
  • 77
  • 1
  • 1
  • 4