我想将检索到的数据推入数组,但只推入第一个对象.
const arr = [{ name: 'name1',item: [] },{ name: 'name2',item: [] }];
routes.forEach((elementRoute) => {
const { methods } = elementRoute;
for (const m in methods) {
let { title } = methods[m];
arr[0].item.push({
name: title,request: { method: m,},});
}
});
我的路由数组是这样的:
[
{
methods: {
get: {
title: 'get users',}
];
它只推送到item数组的第一个对象中.这是我实际上想要得到的结果:
[
{
"name": "name1","item": [
{ "name": "get users","request": { "method": "get" } } }
]
},{
"name": "name2","request": { "method": "get" } } }
]
}
]
最佳答案
您还需要迭代arr来填充所有项目.
原文链接:https://www.f2er.com/js/531197.htmlconst
arr = [{ name: 'name1',item: [] }],routes = [{ methods: { get: { title: 'get users' } } },{ methods: { get: { title: 'get user id' },delete: {} } },];
arr.forEach(({ item }) =>
routes.forEach(({ methods }) => {
for (const method in methods) {
let { title: name = 'Not specified' } = methods[method];
item.push({ name,request: { method } });
}
})
);
console.log(arr);
.as-console-wrapper { max-height: 100% !important; top: 0; }