gpt4 book ai didi

javascript - 如何动态扩展对象?

转载 作者:行者123 更新时间:2023-11-30 17:59:34 25 4
gpt4 key购买 nike

这是一个用于 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'}
}
}

最佳答案

如果您使用的是 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'};

关于javascript - 如何动态扩展对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17369300/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com