如何动态扩展对象?

时间:2013-06-28 16:20:49

标签: javascript jquery fuelux

这是用于jquery库的数据示例,但是我的数据是动态的而不是硬编码的。

var tree_data = {
    'for-sale' : {name: 'For Sale', type: 'folder'} ,
    'vehicles' : {name: 'Vehicles', type: 'folder'} ,
    'rentals' : {name: 'Rentals', type: 'folder'}   ,
    'real-estate' : {name: 'Real Estate', type: 'folder'}   ,
    'pets' : {name: 'Pets', type: 'folder'} ,
    'tickets' : {name: 'Tickets', type: 'item'} ,
    'services' : {name: 'Services', type: 'item'}   ,
    'personals' : {name: 'Personals', type: 'item'}
}

所以,我的问题是,如果我有这个例子:

 var tree_data = {
        'for-sale' : {name: 'For Sale', type: 'folder'} ,
        'vehicles' : {name: 'Vehicles', type: 'folder'} 
}

我将如何添加

 rentals' : {name: 'Rentals', type: 'folder'}   ,
        'real-estate' : {name: 'Real Estate', type: 'folder'}   

在tree_data已经创建之后?

我还需要为此代码执行此操作,如果您可以为两者提供示例。

tree_data['for-sale']['additionalParameters'] = {
    'children' : {
        'appliances' : {name: 'Appliances', type: 'item'},
        'arts-crafts' : {name: 'Arts & Crafts', type: 'item'},
        'clothing' : {name: 'Clothing', type: 'item'},
        'computers' : {name: 'Computers', type: 'item'},
        'jewelry' : {name: 'Jewelry', type: 'item'},
        'office-business' : {name: 'Office & Business', type: 'item'},
        'sports-fitness' : {name: 'Sports & Fitness', type: 'item'}
    }
}

1 个答案:

答案 0 :(得分:2)

如果你正在使用jQuery ....尝试使用$ .extend()

http://api.jquery.com/jQuery.extend/

...否则

var tree_data = {
        'for-sale' : {name: 'For Sale', type: 'folder'} ,
        'vehicles' : {name: 'Vehicles', type: 'folder'} 
};

tree_data['rentals'] = {name: 'Rentals', type: 'folder'}; 
tree_data['real-estate'] = {name: 'Real Estate', type: 'folder'};