Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add element to array associative arrays

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.

like image 682
Dennis G Avatar asked Dec 19 '11 14:12

Dennis G


Video Answer


2 Answers

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...});.

like image 101
James Montagne Avatar answered Sep 27 '22 21:09

James Montagne


This is an array of objects.

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

like image 27
SLaks Avatar answered Sep 27 '22 20:09

SLaks