简体   繁体   中英

Dynamically add items to javascript object

I defined this:

var data ={};

I want to get somehting like this for each "line" in the object:

{field1: "bananas", field2:'test', field3:111, field4:"23.4", field5:"bob"},
{field1: "fruit", field2:'test again', field3:222, field4:"30", field5:"john"}

I know I can do this to add dynamic and static data:

data['field1']= docType;
    data['field2'] = docRef;
    data['field3'] = "test3";
    data['field4'] = mydynamicdata;
    data['field5'] = "test5";

But how can I add different items lines? This code would only add a item set, right? How can I add a second one?

thank you!

You need an Array of Objects - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array

var data = [];

data.push({field1: "bananas", field2:'test', field3:111, field4:"23.4", field5:"bob"})
data.push({field1: "fruit", field2:'test again', field3:222, field4:"30", field5:"john"})

Then you can make changes like this:

data[0]['field1'] = 'new value'
//or:
data[0].field1 = 'new value'

Where 0 is the index of the item inside of the list. So data[1] would be the second object, and so on...

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