Hawker
Hawker

Reputation: 23

javascript array of object with key

I've been searching and searching and haven't found a solution...even though, likely, it's simple. How do I create something that will give me this:

myArray['key1'].FirstName = "First1";   
myArray['key1'].LastName = "Last1";   
myArray['key2'].FirstName = "First2";  
myArray['key2'].LastName = "Last2";  
myArray['key3'].FirstName = "First3";   
myArray['key3'].LastName = "Last3";

And then say something like, alert(myArray['key2'].FirstName);
And will I be able to iterate through it like:

for(i=0; i < myArray.length; i++){
    //do whatever
}

Thanks in advance!

Upvotes: 2

Views: 20769

Answers (4)

G. Mansour
G. Mansour

Reputation: 696

In JavaScript we use arrays like this, [] for Arrays and Objects are in {}

var MyArray = [
               {FirstName: "Firsname1" , LastName: "Lasname1"},
               {FirstName: "Firsname2" , LastName: "Lasname2"}
              ]

Upvotes: 1

a.u.b
a.u.b

Reputation: 1609

You can init an object something like that:

{
    "key1": {FirstName: "first1", LastName: "last1"}
    "key2": {FirstName: "first2", LastName: "last2"}
    "key3": {FirstName: "first3", LastName: "last3"}
}

Sample function for init your array:

function initArray(){
  for(var i=1; i< count+1; i++) {
        var newElement = {}
    newElement.FirstName = "first" + i;
    newElement.LastName = "last" + i;
    var keyName = "key" + i
    var obj = {};
    myArray[keyName] = newElement
    }
}

Now "myArray["key2"] is accessible.

http://jsfiddle.net/jq5Cf/18/

Upvotes: 3

Indhu
Indhu

Reputation: 399

Your myarray variable construction is in notation of objects of objects.

var myArray = {'key1':
    {
        'FirstName' : "First1",
      'LastName' : "Last1"
    }};

In order to access the values should be like array of objects.

var myArray = [
    {
    'FirstName' : "First1",
      'LastName' : "Last1"
    },

];

or notation can be like below:

var data = {
    code: 42,
    items: [{
        id: 1,
        name: 'foo'
    }, {
        id: 2,
        name: 'bar'
    }]
};

Upvotes: 0

Dale
Dale

Reputation: 10469

You can't do what you're trying to do in javascript! (because javascript can't do associative arrays)

I would go for an object which has an internal array to store other things

var container = {};
container.things = [];
container.things.push({FirstName: 'First1', LastName: 'Last1'});

now you can do..

for(var i in container.things) {
    alert(container.things[i].FirstName);
}

Upvotes: 1

Related Questions