Computer >> 컴퓨터 >  >> 프로그램 작성 >> JavaScript

속성이 JavaScript에서 값을 포함하는 객체의 필터 배열

<시간/>

다음과 같은 객체 배열이 있다고 가정해 보겠습니다. -

const arr = [{
   name: 'Paul',
   country: 'Canada',
}, {
   name: 'Lea',
   country: 'Italy',
}, {
   name: 'John',
   country: 'Italy',
}, ];

문자열 키워드에 따라 객체 배열을 필터링하는 방법을 고안해야 합니다. 검색은 개체의 모든 속성에서 이루어져야 합니다.

예를 들어 -

When we type "lea", we want to go through all the objects and all their properties to return the objects that contain "lea".
When we type "italy", we want to go through all the objects and all their properties to return the objects that contain italy.

예시

이에 대한 코드는 -

const arr = [{
      name: 'Paul',
      country: 'Canada',
   }, {
      name: 'Lea',
      country: 'Italy',
   }, {
      name: 'John',
      country: 'Italy',
}, ];
const filterByValue = (arr = [], query = '') => {
   const reg = new RegExp(query,'i');
   return arr.filter((item)=>{
      let flag = false;
      for(prop in item){
         if(reg.test(item[prop])){
            flag = true;
         }
      };
      return flag;
   });
};
console.log(filterByValue(arr, 'ita'));

출력

콘솔의 출력은 -

[
   { name: 'Lea', country: 'Italy' },
   { name: 'John', country: 'Italy' }
]