Skip to content
Advertisement

loop in all property of model in typescript and nodejs

i have a generic model for get all items from Schema .

export interface FilterViewModel<T> {
    filters: T
}

now i use that by this model :

GetAllUsersPaging(items: FilterViewModel<GetAllUserFilter>)

and this is items of my models :

   export interface GetAllUserFilter {
    blocked: boolean,
    emailConfirmed: boolean,
    isActive: boolean,
    isDeleted: boolean,
    personalVerified: boolean,
    phoneNumberConfirmed: boolean,
    phoneNumber: string
}

now i want to search in all filters item and push that in the variable . i write this code but it not worked and not go loop in the all items and just once loop .

    async GetAllUsersPaging(items: FilterViewModel<GetAllUserFilter>) {

    let query: any = [];


    [items.filters].forEach((element) => {

        if (!element.phoneNumber) {
            query.push(element);
        } else {
            query.push({ phoneNumber: { $regex: `(.*)${element.phoneNumber}(.*)` } });
        }

    });

}

now whats the problem ? how can i loop in all items in items.filters ???

Advertisement

Answer

items.filters looks like an object instead of an array, and I think your idea is loop thought all key of GetAllUserFilter and append them, their value to query array.

You can use Object.keys to get all keys of an object, then loop thought them to check their name and value object the object at the key.

async GetAllUsersPaging(items: FilterViewModel<GetAllUserFilter>) {

  const query: any = [];

  Object.keys(items.filters).forEach(key  => {
    const value = items.filters[key as keyof GetAllUserFilter];
    if (key === 'phoneNumber' && value) {
      query.push({ phoneNumber: { $regex: `(.*)${value}(.*)` } });
    } else {
      query.push({ [key]: value }); // ex: { blocked: true }
    }
  });
}
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement