-2

我在尝试将带有键的对象转换为 javascript 中的对象数组时遇到问题

将输入对象转换为类似于所需输出数组的结构的最佳方法是什么?

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,
    }],
}];
4

2 回答 2

0

Object.keys()函数非常适合这样的事情。

试试这个:

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

或者,ES6

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

哪个应该给你:

[
   { screen: HomeScene, path: '/' },
   { screen: AboutScreen, path: '/about' } 
]
于 2018-07-15T02:01:12.600 回答
0

我能够实现如下。这有助于我对我在 react-native-web 应用程序中使用的 react-navigation 和 react-routerv4 使用相同的路由对象。

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);
于 2018-07-15T13:38:54.750 回答