P
P
Pavel Tkachenko2018-04-08 18:15:54
JavaScript
Pavel Tkachenko, 2018-04-08 18:15:54

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' ] }
];

You need to select all matches pathand push from those that matched to the one you are looking for methods, and delete the matched
Script:
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++
    }
});

As a result, where there are 4 or more matching elements, I have something like this:
{ path: '/client/123', methods: [ 'POST', 'GET', 'DELETE' ] },
{ path: '/client/123', methods: [ 'PUT' ] }

And it should be:
{ path: '/client/123', methods: [ 'POST', 'GET', 'DELETE', 'PUT' ] }

I tried and delete routes[j], but there the removal works generally before the condition is met and NodeJS swears that it is routes[j].pathnot defined.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Spirin, 2018-04-08
@Pavel_Tkachenko

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 question

Ask a Question

731 491 924 answers to any question