如何在javascript中使用for循环创建字典?
我有以下资料:如何在javascript中使用for循环创建字典?,javascript,axios,Javascript,Axios,我有以下资料: children: [ { name: 'test', path: 'test', meta: { label: 'test', link: 'test' }, component: lazyLoading('test/basic') }, { name: 'test', path: 'test', meta: {
children: [
{
name: 'test',
path: 'test',
meta: {
label: 'test',
link: 'test'
},
component: lazyLoading('test/basic')
},
{
name: 'test',
path: 'test',
meta: {
label: 'test',
link: 'test'
},
component: lazyLoading('test/Basic')
},
{
name: 'test',
path: 'test',
meta: {
label: 'test',
link: 'test'
},
component: lazyLoading('test/Basic')
}
]
我希望遵循此结构,但使用API调用返回的每条记录以编程方式创建每个字典
示例api调用
function getData() {
axios.get(Url + input.value)
.then(function (response) {
json_data = response.data;
});
}
因此,在python中,这可能类似于:
test_list=[]
for item in json_data:
dict = {
name: item.name
path: item.path
meta: {
label: item.label,
link: item.link,
},
component: lazyLoading('testitem/basic')
},
test_list.append(dict)
children: test_list
如何用javascript实现这一点?在完成python之后,我学习javascript非常困难
更新:
这是我正在使用的完整代码块
export default {
name: 'test',
meta: {
icon: 'fa-android',
expanded: false
},
children: [
{
name: 'test',
path: 'test',
meta: {
label: 'test',
link: 'test'
},
component: lazyLoading('test/Basic')
}
]
}
你非常接近:
const children = [];
json_data.forEach(item => {
const dict = {
name: item.name,
path: item.path,
meta: {
label: item.label,
link: item.link,
},
component: lazyLoading('testitem/basic'),
}
children.push(dict);
});
那么,您是否要将每个字典推到“children”(即列表)中?是的,列表数组在循环之前初始化,在每次迭代中,我只是将新形成的dict对象放入其中。这不是你需要的吗?在行动中,孩子们是一个列表吗?看起来子项是一个键,列表是值?也许在JS中,这与children=list是同一件事?您的代码不清楚children属于什么。不能只做子项:test_list,冒号表示它是对象中的键值对。如果是这样的话,那么您可以这样初始化它:children:[],然后使用obj.children.pushitem推送项目。我写了一篇新文章,因为我意识到我的问题不完整,而且我没有提供足够的信息。