I am currently new to to vuejs and javascript. I want to create an array of "users" inside an entity called "service center". Here is my code.
data() {
return {
serviceCenters: [],
users:[],
currentServiceCenter: null,
currentUser: null,
currentIndex: -1,
currentUserIndex: -1,
id: "",
searchValue: "",
};
Here i have 2 arrays in the data object. serviceCenters which is the array that includes the list of all service centers and a users array which has the list of all users. However each service center has its own list of users in it where i can push or pop a user from. The list of service centers is returned using an api call in spring-boot. Here is the API call.
retrieveServiceCenters() {
ServiceCenterService.getAllServiceCenters()
.then((response) => {
this.serviceCenters = response.data;
console.log(response.data);
})
.catch((e) => {
console.log(e);
});
},
Any help would be highly appreciated.
CodePudding user response:
You need to find the user
with the given id
in the users
list and do the same for serviceCenter
, then check if serviceCenter.users
already an array, then add the user
to if not create new array and add the user
to it too.
addUserToServiceCenters(userId, serviceCenterId) {
const user = this.users.find(user => user.id === id);
const serviceCenter = this.serviceCenters.find(s => s.id === serviceCenterId)
serviceCenter.users = Array.isArray(serviceCenter.users) : [...serviceCenter.users, user] : [user]
}