0

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

2 Answers 2

1

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,
    }],
  });
})
Sign up to request clarification or add additional context in comments.

2 Comments

Its throwing error. this.students is array [1,2,3,4],Same for others type.this.students coming as undefined.
Sorry its working as expected.Thanks for your help.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.