Answer the question
In order to leave comments, you need to log in
Removing an object from an array in NodeJS or a bad script?
The essence of the problem is that the script does not work a little correctly ... I can not figure it out on my own.
I have an array of objects:
var routes = [
{ path: '/login', methods: [ 'GET' ] },
{ path: '/login', methods: [ 'POST' ] },
{ path: '/admin', methods: [ 'GET' ] },
{ path: '/admin', methods: [ 'POST' ] },
{ path: '/admin', methods: [ 'PUT' ] },
{ path: '/admin/mylogin', methods: [ 'GET' ] },
{ path: '/admin/mylogin', methods: [ 'POST' ] },
{ path: '/admin/mylogin/:user', methods: [ 'GET' ] },
{ path: '/admin/mylogin/:user', methods: [ 'POST' ] },
{ path: '/client', methods: [ 'GET' ] },
{ path: '/client', methods: [ 'POST' ] },
{ path: '/client/123', methods: [ 'GET' ] },
{ path: '/client/123', methods: [ 'POST' ] },
{ path: '/client/123', methods: [ 'DELETE' ] },
{ path: '/client/123', methods: [ 'PUT' ] },
{ path: '/', methods: [ 'GET' ] }
];
path
and push from those that matched to the one you are looking for methods
, and delete the matched routes.forEach((element, i) => {
j = 0;
while(j < routes.length) {
if (routes[j].path === element.path && routes[j].methods !== element.methods) {
element.methods.push(routes[j].methods[0]);
routes.splice(j,1)
}
j++
}
});
{ path: '/client/123', methods: [ 'POST', 'GET', 'DELETE' ] },
{ path: '/client/123', methods: [ 'PUT' ] }
{ path: '/client/123', methods: [ 'POST', 'GET', 'DELETE', 'PUT' ] }
delete routes[j]
, but there the removal works generally before the condition is met and NodeJS swears that it is routes[j].path
not defined.
Answer the question
In order to leave comments, you need to log in
const groupedRoutes = Object.values(routes.reduce((map, { path, methods }) => {
map[path] = map[path] ?
{ path, methods: [ ...map[path].methods, ...methods ] } :
{ path, methods };
return map;
},{}));
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question