views:

51

answers:

6

What I want to do with the fs object is to add multiple "items" to the fs.items property. How can I do this? You can see my attempt below, obviously this does not work.

I am a beginner, go easy on me :)

Thanks...

var fs = {
    name:'test',
    items:[]
};

fs.items = {
    name:'item1',
    value:1
};

fs.items = {
    name:'item2',
    value:2
}
+9  A: 

You could use "push":

fs.items.push( { 
    name:'item1',
    value:1
});

fs.items.push( {
    name:'item2',
    value:2
});

The push() function will add entries to an existing array

Philippe Leybaert
you all beat me to it
mcgrailm
+1  A: 
fs.items.push('item1', 'item2'); // fs.items is now ['item1', 'item2']
Aaron
A: 
var fs = { 
    name:'test', 
    items:
    [
    {name:'item1', value:1},
    {name:'item2', value:2}
    ] 
}; 

Newline placement is arbitrary, of course.

Seva Alekseyev
A: 
fs.items[0] = {
    name:'item1',
    value:1
};

fs.items[1] = {
    name:'item2',
    value:2
}
Michael Paulukonis
+1  A: 

if you want to add an entry to an array, you have to use .push or item[...]

fs.items.push( {
    name:'item1',
    value:1
});

fs.items['item2'] = {
    name:'item2',
    value:2
});
oezi
+1  A: 

If you know the items on definition you can inline them like this:

var fs = {
    name:'test',
    items:[
      { name: 'item1', value: 1},
      { name: 'item2', value: 2}
    ]
};

Else you can use the Array push function.

haffax