9

All examples of adding new elements to associative arrays are going the "easy" way and just have a one dimensional array - my problem of understanding is having arrays within arrays (or is it objects in arrays?).

I have the following array:

var test = [
            {
                value: "FirstVal",
                label: "My Label 1"
            },
            {
                value: "SecondVal",
                label: "My Label 2"
            }
           ];

Two questions: How to generate this array of associative arrays (yes... object) from scratch? How to add a new element to an existing array?

Thanks for helping me understand javascript.

Community
  • 1
  • 1
Dennis G
  • 21,405
  • 19
  • 96
  • 133
  • 1
    What does _from scratch_ mean? – SLaks Dec 19 '11 at 14:14
  • 1
    This might be useful: [Javascript: Adding to an associative array](http://stackoverflow.com/questions/8328508/javascript-adding-to-an-associative-array/8328541#8328541) – jabclab Dec 19 '11 at 14:15
  • Bad wording... "from scratch" simply meaning - new. Basically it is the same as starting with an empty array and adding elements to it - your replies already answer this :-) – Dennis G Dec 19 '11 at 14:18

4 Answers4

10

I'm not exactly sure what you mean by "from scratch", but this would work:

var test = [];  // new array

test.push({
                value: "FirstVal",
                label: "My Label 1"
            });  // add a new object

test.push({
                value: "SecondVal",
                label: "My Label 2"
            });  // add a new object

Though the syntax you posted is a perfectly valid way of creating it "from scratch".

And adding a new element would work the same way test.push({..something...});.

James Montagne
  • 77,516
  • 14
  • 110
  • 130
4

This is an array of objects.

You can put more objects in it by calling test.push({ ... })

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
2
var items = [{name:"name1", data:"data1"}, 
             {name:"name2", data:"data2"}, 
             {name:"name3", data:"data3"}, 
             {name:"name4", data:"data4"}, 
             {name:"name5", data:"data5"}]

var test = [];

for(var i = 0; i < items.length; i++){
    var item = {};
    item.label = items[i].name;
    item.value = items[i].data;
    test.push(item);
}

makes test equal to

[{label:"name1", value:"data1"}, 
 {label:"name2", value:"data2"}, 
 {label:"name3", value:"data3"}, 
 {label:"name4", value:"data4"}, 
 {label:"name5", value:"data5"}]
Diode
  • 24,570
  • 8
  • 40
  • 51
1

From scratch, the following lines will create an populate an array with objects, using the Array.prototype.push method:

var test = [];          // Create an array
var obj = {};           // Create an object
obj.value = "FirstVal"; // Add values, etc.
test.push(obj);
Rob W
  • 341,306
  • 83
  • 791
  • 678