简体   繁体   中英

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.

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

This is an array of objects.

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

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"}]

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM