0
function deptTypes(items) { 
  return items[Math.floor(Math.random()*items.length)]; 
}
var items = ["a", "b","c","d","e","f"]; 
await queryInterface.bulkInsert('reviews', [...Array(50)].map((review) => (
  {
    user_id: users[Math.floor(Math.random()*users.length)].id, 
    title: faker.name.title(), 
    review: faker.lorem.sentences(6), 
    rating: Math.round(Math.random()*5),
    department_type: deptTypes(items), 
    department_uid: (deptTypes(items) == 'a' ) ? alist[Math.floor(Math.random()*alist.length)].id 
                      :(deptTypes(items) == 'b' ) ? blist[Math.floor(Math.random()*blist.length)].id
                        : (deptTypes(items)== 'c') ? clist[Math.floor(Math.random()*clist.length)].id 
                          : (deptTypes(items) == 'd') ? dlist[Math.floor(Math.random()*dlist.length)].id
                            : (deptTypes(items) == 'e') ? elist[Math.floor(Math.random()*elist.length)].id
                              : flist[Math.floor(Math.random()*flist.length)].id, 
    created_at: new Date(),
    updated_at: new Date()
  }
)), {});

what i'm trying is i need the same deptType item that is assigned to department_type and give department_uid a value based on department_type, but im not getting desired result ... please help

  • const dept = deptTypes(items); at the top, and then use dept everywhere you have deptTypes(items). Otherwise each call to deptTypes will give you a different random number. – James Jul 28 '21 at 18:56
  • thanks, but i already tried as you said ... it gave a table with department_type column with same item in 50 rows so, this didn't work , and what i need is a department_type should be assigned a random value and department_uid should give the same item's id – Aravind Kethireddy Jul 28 '21 at 19:06
  • Sorry yes - the declaration would need to be inside the map function. – James Jul 28 '21 at 19:16

1 Answers1

0

At the top of the map function, declare a variable which will be the dept for this iteration:

await queryInterface.bulkInsert('reviews', [...Array(50)].map((review) => {

  const dept = deptTypes(items);

  return {
    user_id: users[Math.floor(Math.random()*users.length)].id, 
    title: faker.name.title(), 
    review: faker.lorem.sentences(6), 
    rating: Math.round(Math.random()*5),
    department_type: dept,
    department_uid: (dept == 'a' ) ? alist[Math.floor(Math.random()*alist.length)].id 
                      :(dept == 'b' ) ? blist[Math.floor(Math.random()*blist.length)].id
                        : (dept == 'c') ? clist[Math.floor(Math.random()*clist.length)].id 
                          : (dept == 'd') ? dlist[Math.floor(Math.random()*dlist.length)].id
                            : (dept == 'e') ? elist[Math.floor(Math.random()*elist.length)].id
                              : flist[Math.floor(Math.random()*flist.length)].id, 
    created_at: new Date(),
    updated_at: new Date()
  };
}), {});
James
  • 20,957
  • 5
  • 26
  • 41