In my Vue.js application I use a navigation drawer to display the different pages a user has access to. Pages are also only visible if the administrator has activated the related module. Therefore the unique moduleID is set for each page and children. The list is populated by filteredPages[]. This array is the result of displaying only the pages a user has access to. All available pages are stored in my original data source pages[].
To sum this up: A page is only shown if both of these conditions are true:
activatedModules[] contains the moduleID of a page and the children.
userPermissions[] contains the permissions value of a children (or page if there is no children).
My code:
export default {
data: () => ({
pages: [
{
text: 'Team', moduleID: 'm1',
children: [
{ text: 'Dashboard', route:'team/dashboard', permissions: 'p101', moduleID: 'm1-1' },
],
},
{
text: 'Planner', moduleID: 'm2',
children: [
{ text: 'Events', route:'/planner/events', permissions: 'p201', moduleID: 'm2-1' },
{ text: 'Calendar', route:'/planner/calendar', permissions: 'p202', moduleID: 'm2-2' },
],
},
{
text: 'HR', moduleID: 'm3',
children: [
{ text: 'Staff', route:'/hr/staff', permissions: 'p301', moduleID: 'm3-1' },
{ text: 'Config', route:'/hr/config', permissions: 'p302', moduleID: 'm3-2' },
],
},
{
text: 'Admin', moduleID: 'm4',
children: [
{ text: 'Users', route:'/admin/users', permissions: 'p401', moduleID: 'm4-1' },
{ text: 'Security', route:'/admin/security', permissions: 'p402', moduleID: 'm4-2' },
],
},
{ text: 'Support', route:'/support', permissions: 'p50', moduleID: 'm5' },
],
activatedModules: ['m1', 'm1-1', 'm3', 'm3-1', 'm3-2' 'm4', 'm4-1', 'm4-2', 'm5'],
userPermissions: ['p101', 'p301', 'p302', 'p402', 'p50'],
// This is the source for my navigation drawer:
filteredPages: []
}),
computed: {
filterArray() {
// I tried to use filter() but how can I solve the rest?
this.filteredPages = this.pages.filter(function(item) {
for (var this.activatedModules in filter) {
if /* I would assume that I have to write the condition here */
return false;
}
return true;
})
}
}
}
For the code above this should be the output:
filteredPages: [
{
text: 'Team', moduleID: 'm1',
children: [
{ text: 'Dashboard', route:'team/dashboard', permissions: 'p', moduleID: 'm1-1' },
],
},
// Notice that 'm2' is missing here because it is not in activatedModules[]
{
text: 'HR', moduleID: 'm3',
children: [
{ text: 'Staff', route:'/hr/staff', permissions: 'p301', moduleID: 'm3-1' },
{ text: 'Config', route:'/hr/config', permissions: 'p302', moduleID: 'm3-2' },
],
},
{
text: 'Admin', moduleID: 'm4',
children: [
// 'm4-1' is in activatedModules[] but the user doesn't have the permission 'p401' to view this
{ text: 'Security', route:'/admin/security', permissions: 'p402', moduleID: 'm4-2' },
],
},
{ text: 'Support', route:'/support', permissions: 'p50', moduleID: 'm5' },
]
The permissions of a user are stored in Firebase Cloud Firestore like this:
Can you help with the filtering of the array?
This should do it:
computed: {
filteredPages() {
return this.pages.map(page => ({
...page,
children: page.children
// when children is truthy
? page.children.filter(
// filter out those not in `userPermissions`
child => this.userPermissions.includes(child.permissions)
// and those not in `activatedModules`
&& this.activatedModules.includes(child.moduleID)
)
: page.children
})).filter(
// only keep page if in `activatedModules` and...
page => (this.activatedModules.includes(page.moduleID)) &&
// if children is truthy and has length or...
(page.children?.length || (
// if children is falsy and page.permissions in userPermissions
!page.children && this.userPermissions.includes(page.permissions)
))
);
}
}
See it working:
Vue.config.devtools = false;
Vue.config.productionTip = false;
new Vue({
el: '#app',
data: () => ({
pages: [
{
text: 'Team',
moduleID: 'm1',
children: [
{ text: 'Dashboard', route:'team/dashboard', permissions: 'p101', moduleID: 'm1-1' }
],
}, {
text: 'Planner',
moduleID: 'm2',
children: [
{ text: 'Events', route:'/planner/events', permissions: 'p201', moduleID: 'm2-1' },
{ text: 'Calendar', route:'/planner/calendar', permissions: 'p202', moduleID: 'm2-2' },
],
}, {
text: 'HR',
moduleID: 'm3',
children: [
{ text: 'Staff', route:'/hr/staff', permissions: 'p301', moduleID: 'm3-1' },
{ text: 'Config', route:'/hr/config', permissions: 'p302', moduleID: 'm3-2' },
],
}, {
text: 'Admin',
moduleID: 'm4',
children: [
{ text: 'Users', route:'/admin/users', permissions: 'p401', moduleID: 'm4-1' },
{ text: 'Security', route:'/admin/security', permissions: 'p402', moduleID: 'm4-2' },
],
},
{ text: 'Support', route:'/support', permissions: 'p50', moduleID: 'm5' }
],
activatedModules: ['m1', 'm1-1', 'm3', 'm3-1', 'm3-2', 'm4', 'm4-1', 'm4-2', 'm5'],
userPermissions: ['p101', 'p301', 'p302', 'p402', 'p50']
}),
computed: {
filteredPages() {
return this.pages.map(page => ({
...page,
children: page.children
? page.children.filter(
child => this.userPermissions.includes(child.permissions)
&& this.activatedModules.includes(child.moduleID)
)
: page.children
})).filter(
page => (this.activatedModules.includes(page.moduleID))
&& (page.children?.length || (
!page.children && this.userPermissions.includes(page.permissions)
))
);
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<pre v-html="filteredPages" />
</div>
in the code snippet below I used a filter first to filter by activatedModules then used a forEach to filter each object children property by userPermissions, I think you can implement this in your vue component or get an idea about how to tackle the problem (hope this helps):
const pages = [{
text: 'Team',
moduleID: 'm1',
children: [{
text: 'Dashboard',
route: 'team/dashboard',
permissions: 'p1382',
moduleID: 'm1-1'
}, ],
},
{
text: 'Planner',
moduleID: 'm2',
children: [{
text: 'Events',
route: '/planner/events',
permissions: 'p47289',
moduleID: 'm2-1'
},
{
text: 'Calendar',
route: '/planner/calendar',
permissions: 'p283',
moduleID: 'm2-2'
},
],
},
{
text: 'HR',
moduleID: 'm3',
children: [{
text: 'Staff',
route: '/hr/staff',
permissions: 'p34729',
moduleID: 'm3-1'
},
{
text: 'Config',
route: '/hr/config',
permissions: 'p382',
moduleID: 'm3-2'
},
],
},
{
text: 'Admin',
moduleID: 'm4',
children: [{
text: 'Users',
route: '/admin/users',
permissions: 'p3z4',
moduleID: 'm4-1'
},
{
text: 'Security',
route: '/admin/security',
permissions: 'p2u3',
moduleID: 'm4-2'
},
],
},
{
text: 'Support',
route: '/support',
permissions: 'p332j',
moduleID: 'm5'
},
];
const activatedModules = ['m1', 'm3', 'm4', 'm5'];
const userPermissions = ['m1-1', 'm3-1', 'm3-2', 'm4-2'];
// This is the source for my navigation drawer:
let filteredPages = null;
filteredPages = pages.filter(x => activatedModules.includes(x.moduleID));
filteredPages.forEach(x => {
if (x.children)
x.children = x.children.filter(y => userPermissions.includes(y.moduleID));
});
console.log(filteredPages);
Some remarks:
You should not be using function for callbacks, like you started doing for filter, as that will make you lose the right this value. Use arrow functions.
filter cannot do the job on its own, as you need to also generate new objects which may have fewer children. So you should first map to make those narrowed down objects, and then filter.
Without using Vue, you can run the following snippet, which just hard-codes the call to filterArray:
let app = {
computed: {
filterArray() {
this.filteredPages = this.pages.map(item => {
let children = (item.children || []).filter(child =>
this.activatedModules.includes(child.moduleID) &&
this.userPermissions.includes(child.permissions)
);
return (children.length || !item.children)
&& this.activatedModules.includes(item.moduleID)
&& {...item, children};
}).filter(Boolean);
}
},
data: () => ({
pages: [
{
text: 'Team', moduleID: 'm1',
children: [
{ text: 'Dashboard', route:'team/dashboard', permissions: 'p101', moduleID: 'm1-1' },
],
},
{
text: 'Planner', moduleID: 'm2',
children: [
{ text: 'Events', route:'/planner/events', permissions: 'p201', moduleID: 'm2-1' },
{ text: 'Calendar', route:'/planner/calendar', permissions: 'p202', moduleID: 'm2-2' },
],
},
{
text: 'HR', moduleID: 'm3',
children: [
{ text: 'Staff', route:'/hr/staff', permissions: 'p301', moduleID: 'm3-1' },
{ text: 'Config', route:'/hr/config', permissions: 'p302', moduleID: 'm3-2' },
],
},
{
text: 'Admin', moduleID: 'm4',
children: [
{ text: 'Users', route:'/admin/users', permissions: 'p401', moduleID: 'm4-1' },
{ text: 'Security', route:'/admin/security', permissions: 'p402', moduleID: 'm4-2' },
],
},
{ text: 'Support', route:'/support', permissions: 'p50', moduleID: 'm5' },
],
activatedModules: ['m1', 'm1-1', 'm3', 'm3-1', 'm3-2', 'm4', 'm4-1', 'm4-2', 'm5'],
userPermissions: ['p101', 'p301', 'p302', 'p402', 'p50'],
filteredPages: []
}),
};
// Demo, simulate Vue's call to computed.filterArray
let data = app.data();
app.computed.filterArray.call(data);
// Verify output:
console.log(data.filteredPages);
Related
Using Vue3 - Vuerouter4 - Vite
I try to import the components and routes in vue router but I face this error (only for the route that has children in my paths):
my router code:
import { createRouter, createWebHistory } from "vue-router";
import paths from "./path";
import { TokenService } from "#/services/storage.services.js";
function route(options) {
let path = options.path;
let view = options.view;
let name = options.name;
let meta = options.meta ? options.meta : "";
let children = options.children ? options.children : null;
let redirect = options.redirect ? options.redirect : null;
let currentRoute = {
name: name || view,
path,
meta,
component: (resolve) => import(`#/views/${view}.vue`).then(resolve),
};
if (children && Array.isArray(children)) {
children = children.map((path) => {
path.view = view + "/" + path.view;
return path;
});
currentRoute["children"] = children.map((path) => route(path));
}
if (redirect) {
currentRoute["redirect"] = redirect;
}
return currentRoute;
}
// Create a new router
const router = createRouter({
history: createWebHistory(),
routes: paths
.map((path) => route(path))
.concat([{ path: "/:pathMatch(.*)", redirect: "admin/home" }]),
scrollBehavior(to, from, savedPosition) {
if (savedPosition) {
return savedPosition;
}
if (to.hash) {
return { selector: to.hash };
}
return { left: 0, top: 0 };
},
});
export default router;
my paths that are in paths.js:
export default [
{
path: "/admin",
name: "Admin",
view: "Admin",
redirect: "Admin/Home",
children: [
{
path: "Home",
name: "Home",
view: "Home",
meta: {
auth: true,
title: "داشبورد",
},
},
{
path: "TRANSACTION",
name: "TRANSACTION",
view: "Transaction",
meta: {
auth: true,
title: "تراکنش ها",
},
},
{
path: "SMS-MANAGEMENT",
name: "SMSManagement",
view: "SMSManagement",
meta: {
auth: true,
title: "مدیریت پیامک ها",
},
},
{
path: "CAR-LIST",
name: "CAR-LIST",
view: "Car-List",
meta: {
auth: true,
title: "لیست خودرو های اجاره ای",
},
},
{
path: "ADDRENTCAR",
name: "ADDRENTCAR",
view: "AddRentCar",
meta: {
auth: false,
title: "افزودن خودرو اجاره ای",
},
},
{
path: "EDITRENTCAR",
name: "EDITRENTCAR",
view: "AddRentCar",
meta: {
auth: false,
title: "ویرایش خودرو اجاره ای",
},
},
{
path: "USERS",
name: "USERS",
view: "Users",
meta: {
auth: true,
title: "لیست کاربران",
},
},
{
path: "CARS",
name: "CARS",
view: "Cars",
meta: {
auth: true,
title: "لیست خودرو ها",
},
},
{
path: "REQUESTS",
name: "REQUESTS",
view: "REQUESTS",
meta: {
auth: true,
title: "لیست درخواست ها",
},
},
],
},
{
path: "",
name: "MAIN-HOME",
view: "main-home",
meta: {
auth: true,
title: "صفحه اصلی",
public: true,
},
},
{
path: "/PROFILE",
name: "PROFILE",
view: "PROFILE",
meta: {
auth: true,
title: "پروفایل من",
},
},
{
path: "/LOGIN",
name: "LOGIN",
view: "Login",
meta: {
auth: true,
title: "ورود",
},
},
{
path: "/ALLCARS",
name: "ALLCARS",
view: "ALLCARS",
meta: {
public: true,
auth: true,
title: "لیست تمام خودرو ها",
},
},
{
path: "/ABOUTUS",
name: "ABOUTUS",
view: "ABOUTUS",
meta: {
public: true,
auth: true,
title: "درباره ما",
},
},
];
Any ideas what causes the error specifically for my admin route that has children??!!
........................................................................................................................................................................................................................................................................................................................................................................................................................................................................
I changed the "../views/" to "/src/views/" and problem solved.
Seems like using '..' wouldn't make it to the src folder!!!!!
Thank you #Mohammad Masoudi
I have made a separate file for routes.
Here is the structure:
I have a separate folder for every module.
->routes->admin->userRoutes.js,contactRoutes.js etc
Then, inside routes->admin.js I import those files like this:
import contactsRoutes from './admin/customerRoutes'
import userRoutes from './admin/userRoutes'
Again, in router.js, I want to include admin.js so I can use both contactsRoutes and userRoutes inside router.js:
import './routes/admin.js'
Here is our customerRoutes.js this file contacines routes of this module. i means all the routes of customer CRUD
customerRoutes.js
import CustomerList from '#/views/apps/customers/CustomersList.vue';
export default
[{
path: '/customers',
name: 'customers',
component: CustomerList,
title: 'People',
meta: {
breadcrumb: [
{ title: 'All Customers', url: '/customers' },
{ title: 'All Customers', active: true },
],
pageTitle: 'Customers',
rule: 'admin',
authRequired: true
}
},
{
path: '/customers/view/:id',
name: 'customers-view',
component: () =>
import('#/views/apps/customers/CustomerView.vue'),
meta: {
breadcrumb: [
{ title: 'All Customers', url: '/customers' },
{ title: 'All Customers', url: '/customers' },
{ title: 'View', active: true },
],
pageTitle: 'Customers',
rule: 'admin',
authRequired: true
}
}
,
{
path: '/customers',
name: 'customers',
component: () =>
import('#/views/apps/customers/CustomersList.vue'),
meta: {
breadcrumb: [
{ title: 'All Customers', url: '/customers' },
{ title: 'All Customers', active: true },
],
pageTitle: 'Customers',
rule: 'admin',
authRequired: true
}
}, {
path: '/customers/view/:id',
name: 'customers-view',
component: () =>
import ('#/views/apps/customers/CustomerView.vue'),
meta: {
breadcrumb: [
{ title: 'All Customers', url: '/customers' },
{ title: 'All Customers', url: '/customers' },
{ title: 'View', active:true },
],
pageTitle: 'Customers',
rule: 'admin',
authRequired: true
}
},
{
path: '/customers/add',
name: 'customers-add',
component: () =>
import ('#/views/apps/customers/CustomerAdd.vue'),
meta: {
breadcrumb: [
{ title: 'All Customers', url: '/customers' },
{ title: 'All Customers', url: '/customers' },
{ title: 'Add', active : true },
],
pageTitle: 'Customers',
rule: 'admin',
authRequired: true
}
},
{
path: '/customers/edit/:id',
name: 'customers-edit',
component: () =>
import ('#/views/apps/customers/CustomerEdit.vue'),
meta: {
breadcrumb: [
{ title: 'All Customers', url: '/customers' },
{ title: 'All Customers', url: '/customers' },
{ title: 'Edit', active : true },
],
pageTitle: 'Customers',
rule: 'admin',
authRequired: true
}
},];
```
But, it is giving me an error that both variables are not available.
Is there any solution available?
I am trying to test if the logged in user has the appropriate role to see certain items in the dashboard.
I have an array of objects. These are the items that the user may or may not see:
items: [
{ title: 'Guide', icon: '$guide', component: 'Guide', claims: '', size: '', roles: ['superAdmin', 'admin', 'pastor'] },
{ title: 'Courses', icon: '$courses', component: 'Course', claims: '', size: '', roles: ['superAdmin', 'admin', 'pastor'] },
{ title: 'Sections', icon: '$sections', component: 'Sections', claims: '', size: '', roles: ['superAdmin', 'admin'] },
{ title: 'Units', icon: '$units', component: 'Units', claims: '', size: '', roles: ['superAdmin', 'admin'] },
{ title: 'Groups', icon: '$groups', component: 'Groups', claims: '', size: '', roles: ['superAdmin', 'admin', 'pastor'] },
{ title: 'Users', icon: '$users', component: 'Users', claims: '', size: '', roles: ['superAdmin', 'admin', 'pastor'] },
{ title: 'FAQ', icon: '$faq', component: 'FAG', claims: '', size: '', roles: ['superAdmin', 'admin', 'pastor'] },
]
and an admin object. This is the user and their permission roles:
cid: (...)
email: (...)
emailVerified: (...)
fullPath: (...)
id: undefined
roles: Array(2)
0: "member"
1: "pastor"
Here is my code:
const hasRole = this.items.filter(val => this.admin.roles.includes(val.roles))
return hasRole
This code no longer works because the items.roles used to only be a string but I have now made it an array of roles.
I have tried multiple combinations but am struggling to figure this out.
Use Array.some() to test if any element in an array satisfies a condition. In this case, the condition would be if the element is found in another array.
const hasRole = this.items.filter(val =>
this.admin.roles.some(role => val.roles.includes(role))
)
return hasRole
Change to Array.every() instead if all roles in the this.admin object should be included to result in a positive result.
I see there is already a solution, anyway I post also mine. If you want to filter the array and get only items with specified role then you can try this:
let items= [
{ title: 'Guide', icon: '$guide', component: 'Guide', claims: '', size: '', roles: ['superAdmin', 'admin', 'pastor'] },
{ title: 'Courses', icon: '$courses', component: 'Course', claims: '', size: '', roles: ['superAdmin', 'admin', 'pastor'] },
{ title: 'Sections', icon: '$sections', component: 'Sections', claims: '', size: '', roles: ['superAdmin', 'admin'] },
{ title: 'Units', icon: '$units', component: 'Units', claims: '', size: '', roles: ['superAdmin', 'admin'] },
{ title: 'Groups', icon: '$groups', component: 'Groups', claims: '', size: '', roles: ['superAdmin', 'admin', 'pastor'] },
{ title: 'Users', icon: '$users', component: 'Users', claims: '', size: '', roles: ['superAdmin', 'admin', 'pastor'] },
{ title: 'FAQ', icon: '$faq', component: 'FAG', claims: '', size: '', roles: ['superAdmin', 'admin', 'pastor'] },
]
let admin = {
roles: {
0: "member",
1: "pastor"
}
}
let filtered = {}
for(role in admin.roles){
itemsWithSpecificRole = items.filter(val => val.roles.includes(admin.roles[role]))
Object.assign(filtered, itemsWithSpecificRole)
}
console.log(filtered)
I have the following made-up JavaScript array of objects:
const permissions = [
{
moduleEnabled: true,
moduleId: 1,
moduleName: 'Directory'
},
{
moduleEnabled: true,
moduleId: 2,
moduleName: 'Time off'
},
{
moduleEnabled: false,
moduleId: 3,
moduleName: 'Tasks'
},
{
moduleEnabled: false,
moduleId: 4,
moduleName: 'Documents'
}
]
I also have the following array of objects based on a collection of widgets that are available to be displayed:
const widgets = [
{
id: 1,
moduleId: 2,
title: 'Your time off'
},
{
id: 2,
moduleId: 1,
title: 'Your colleagues'
},
{
id: 3,
moduleId: 3,
title: 'Your tasks'
},
{
id: 4,
moduleId: 5,
title: 'Your sales pipeline'
},
{
id: 5,
moduleId: 4,
title: 'Your documents'
},
{
id: 6,
moduleId: 6,
title: 'Your legal cases'
}
]
What I'd like to do is to reduce the array of objects widgets to a new array of objects filteredWidgets based on the values in the permissions array of objects, these being whether the moduleId is found, and also where the moduleEnabled is true.
I've tried the code below, but it's not working:
const filteredWidgets = []
for (const permission in permissions) {
const found = widgets.filter((item) => item.moduleId === permission.moduleId && permission.moduleEnabled)
if (found) {
filteredWidgets.push(found)
}
}
console.log('filteredWidgets\n', filteredWidgets)
Any help will be greatly appreciated. Thanks in advance.
Edit: include expected output:
const filteredWidgets = [
{
id: 1,
moduleId: 2,
title: 'Your time off'
},
{
id: 2,
moduleId: 1,
title: 'Your colleagues'
}
]
In your filter function, check for any permission which matches the given criteria:
const filteredWidgets = widgets.filter(widget =>
permissions.find(permission =>
(permission.moduleId === widget.moduleId) && permission.moduleEnabled));
I think with .reduce() and .find() combination the following can work for you:
const permissions = [{moduleEnabled: true, moduleId: 1, moduleName: 'Directory' }, { moduleEnabled: true, moduleId: 2, moduleName: 'Time off' }, { moduleEnabled: false, moduleId: 3, moduleName: 'Tasks' }, { moduleEnabled: false, moduleId: 4, moduleName: 'Documents' }];
const widgets = [{ id: 1, moduleId: 2, title: 'Your time off' }, { id: 2, moduleId: 1, title: 'Your colleagues' }, { id: 3, moduleId: 3, title: 'Your tasks' }, { id: 4, moduleId: 5, title: 'Your sales pipeline' }, { id: 5, moduleId: 4, title: 'Your documents' },{ id: 6, moduleId: 6, title: 'Your legal cases'}]
const result = widgets.reduce((a, c) => {
const found = permissions.find(e => e.moduleId === c.moduleId)
return found && found.moduleEnabled ? a.concat(c) : a;
}, []);
console.log(result);
I hope this helps!
You could take an object with the allowed ids and filter by moduleId.
const
permissions = [{ moduleEnabled: true, moduleId: 1, moduleName: 'Directory' }, { moduleEnabled: true, moduleId: 2, moduleName: 'Time off' }, { moduleEnabled: false, moduleId: 3, moduleName: 'Tasks' }, { moduleEnabled: false, moduleId: 4, moduleName: 'Documents' }],
widgets = [{ id: 1, moduleId: 2, title: 'Your time off' }, { id: 2, moduleId: 1, title: 'Your colleagues' }, { id: 3, moduleId: 3, title: 'Your tasks' }, { id: 4, moduleId: 5, title: 'Your sales pipeline' }, { id: 5, moduleId: 4, title: 'Your documents' }, { id: 6, moduleId: 6, title: 'Your legal cases' }],
allowed = permissions.reduce((o, { moduleEnabled, moduleId }) =>
({ ...o, [moduleId]: moduleEnabled }), {}),
filteredWidgets = widgets.filter(({ moduleId }) => allowed[moduleId]);
console.log(filteredWidgets);
.as-console-wrapper { max-height: 100% !important; top: 0; }
I have a solution using reduce
But first, you have to create a Map and use that to create an Object with Object.fromEntries(), and then finally use the reduce.
const permissions = [
{
moduleEnabled: true,
moduleId: 1,
moduleName: 'Directory'
},
{
moduleEnabled: true,
moduleId: 2,
moduleName: 'Time off'
},
{
moduleEnabled: false,
moduleId: 3,
moduleName: 'Tasks'
},
{
moduleEnabled: false,
moduleId: 4,
moduleName: 'Documents'
}
]
const widgets = [
{
id: 1,
moduleId: 2,
title: 'Your time off'
},
{
id: 2,
moduleId: 1,
title: 'Your colleagues'
},
{
id: 3,
moduleId: 3,
title: 'Your tasks'
},
{
id: 4,
moduleId: 5,
title: 'Your sales pipeline'
},
{
id: 5,
moduleId: 4,
title: 'Your documents'
},
{
id: 6,
moduleId: 6,
title: 'Your legal cases'
}
]
const permissonsMap = permissions.map((child,index) => {
return [child.moduleId, {...child}]
})
const permissionsObj = Object.fromEntries(permissonsMap);
//console.log(permissionsObj);
const filteredWidgets = widgets.reduce((aggArr,currItem) => {
if (permissionsObj[currItem.moduleId] && permissionsObj[currItem.moduleId].moduleEnabled){
aggArr.push(currItem);
}
return aggArr;
},[])
console.log(filteredWidgets);
Important lines are:
const permissonsMap = permissions.map((child,index) => {
return [child.moduleId, {...child}]
})
const permissionsObj = Object.fromEntries(permissonsMap);
//console.log(permissionsObj);
const filteredWidgets = widgets.reduce((aggArr,currItem) => {
if (permissionsObj[currItem.moduleId] && permissionsObj[currItem.moduleId].moduleEnabled){
aggArr.push(currItem);
}
return aggArr;
},[])
console.log(filteredWidgets);
I have the following:
children: [
{
name: 'test',
path: 'test',
meta: {
label: 'test',
link: 'test'
},
component: lazyLoading('test/basic')
},
{
name: 'test',
path: 'test',
meta: {
label: 'test',
link: 'test'
},
component: lazyLoading('test/Basic')
},
{
name: 'test',
path: 'test',
meta: {
label: 'test',
link: 'test'
},
component: lazyLoading('test/Basic')
}
]
I want to follow this structure, but programmatically create each dictionary using each record returned from an API call.
example api call
function getData() {
axios.get(Url + input.value)
.then(function (response) {
json_data = response.data;
});
}
so in python this would probably look something like:
test_list=[]
for item in json_data:
dict = {
name: item.name
path: item.path
meta: {
label: item.label,
link: item.link,
},
component: lazyLoading('testitem/basic')
},
test_list.append(dict)
children: test_list
How can I accomplish this in javascript? I'm having a real hard time learning javascript after doing python.
UPDATE:
This is the full code block that I am working with.
export default {
name: 'test',
meta: {
icon: 'fa-android',
expanded: false
},
children: [
{
name: 'test',
path: 'test',
meta: {
label: 'test',
link: 'test'
},
component: lazyLoading('test/Basic')
}
]
}
You were very close:
const children = [];
json_data.forEach(item => {
const dict = {
name: item.name,
path: item.path,
meta: {
label: item.label,
link: item.link,
},
component: lazyLoading('testitem/basic'),
}
children.push(dict);
});