-2

I am struck on a problem trying to Convert a Object with keys to an array of objects in javascript

What is the best way to convert the input Object to resemble the structure of the desiredOutput array?

const routes = {
    Home: {
        screen: HomeScene,
        path: '/'
    },
    About: {
        screen: AboutScreen,
        path: '/about'
    }
};

const output_routes = 
[{
    component: Layout,
    routes: [{
        path: '/',
        exact: true,
        component: HomeScene,
    },
    {
        path: '/about',
        exact: true,
        component: AboutScreen,
    }],
}];
Taki
  • 17,320
  • 4
  • 26
  • 47
  • This isn't a bad question but maybe don't word it like a home work question. Do a little bit of research try to solve the problem your self and post a failed solution or a bulky solution and people will be more receptive. I've learned the hard way so don't sweat it. – haelmic Jul 15 '18 at 03:19

2 Answers2

0

The Object.keys() function is great for something like this.

Give this a try:

function toArray(obj) {
  return Object.keys(obj).map(function(key) {
    return obj[key];
  });
}

or, ES6:

const toArray = (obj) => Object.keys(obj).map(key => obj[key]);

Which should give you:

[
   { screen: HomeScene, path: '/' },
   { screen: AboutScreen, path: '/about' } 
]
Allan of Sydney
  • 1,410
  • 14
  • 23
0

I was able to implement as below. This helps me to use same route object for both react-navigation and react-routerv4 I am using in my react-native-web app.

const ROUTES = {
    Home: {
        screen: 'HomeScene',
        path: '/'
    },
    About: {
        screen: 'AboutScreen',
        path: '/about'
    }
};

//const toArray = (ROUTES) => Object.keys(ROUTES).map(key => ROUTES[key]);
const routes_new = Object.keys(ROUTES).map((routeName,idx)=> {
const { screen: Screen, path } = ROUTES[routeName]; 
const routeProps = 
      {
                path,
                component: Screen,
                key: idx,
                exact: true
            }; 
  return routeProps

})

routes_server = [];
routes_server.push({
        component:'Layout',
    });

routes_new.push({component: 'NotFoundScene'})
routes_server.push({routes:routes_new})
console.log(routes_server);