user2410266
user2410266

Reputation: 551

Vue.js Adding object from multiple arrays

I am adding different objects to an array based on certain conditions.I think i am repeating the same code multiple times.Any suggestion to write the codes in better way.

this.users.forEach((item) => {
    const student = this.students.find((id) => item.user.id == id);
    if(student) {
      this.schools.push({
        'type':'Student',
        'info':[{
          'name': item.name,
          'id': item.Id,
        }],
      });
    }
   const teacher = this.teachers.find((id) => item.user.id == id);
    if(teacher) {
      this.schools.push({
        'type':'Teacher',
        'info':[{
          'name': item.name,
          'id': item.Id,
        }],
      });
    }
    const staff = this.staffs.find((id) => item.user.id == id);
    if(staff) {
      this.schools.push({
        'type':'Staff',
        'info':[{
          'name': item.name,
          'id': item.Id,
        }],
      });
    }
  });
},

Upvotes: 0

Views: 373

Answers (2)

AhmadVahedi
AhmadVahedi

Reputation: 57

In your code there is 3 push to array that have only different type, instead of this.schools.push…. you can create a method and pass type and item to it (I can’t see your data here but when you use this.schools that means that is a data so you can call it the same way in method too)

this.users.forEach((item) => {
    const student = this.students.find((id) => item.user.id == id);
    if(student) {
       this.pushToArray('Student', item)
    }
   const teacher = this.teachers.find((id) => item.user.id == id);
    if(teacher) {
       this.pushToArray('Teacher', item)
    }
    const staff = this.staffs.find((id) => item.user.id == id);
    if(staff) {
       this.pushToArray('Staff', item)
    }
  });
},

pushToArray: function (type, item) {
   this.schools.push({
    'type': type,
    'info':[{
      'name': item.name,
      'id': item.Id,
    }],
  });
},

Upvotes: 1

akuiper
akuiper

Reputation: 214957

You can create a userType object that maps from id to Type first, and then look up the Type by user id later.

let userType = {}

this.students.forEach(id => userType[id] = 'Student')
this.teachers.forEach(id => userType[id] = 'Teacher')
this.staffs.forEach(id => userType[id] = 'Staff')

this.users.forEach((item) => {
  this.schools.push({
    'type': userType[item.Id],
    'info':[{
      'name': item.name,
      'id': item.Id,
    }],
  });
})

Upvotes: 1

Related Questions