Barcha json elementlarini lodash.js bilan qidiring

json ob'ekt jildim:

  var companies= [
    { id: 1, name: "Test Company", admin: "Test Admin" },
    { id: 2, name: "Another Company", admin: "Test Admin", country: 'Spain' },
    {id: 3, ism: "Yangi kompaniya", o'tilganlik sanasi: "Admin 4"},
    {id: 4, ism: "Bepul kompaniya", o'tilganlik sanasi: "Jhon Miller", shahar: "Nyu-York"}
];

va yangi jsonni parametr sifatida (filtri) topshiradigan elementlar bilan qaytish uchun funksiya yozyapman. Men oddiyman

   function searchBooks(companies,filter){
    var result;
      if (typeof filter=== "undefined" ||  filter.length==0) {
          result = companies;
      } else {
        result = _.filter(companies, function (c) {
         return _.includes(_.lowerCase(c.name),_.lowerCase(filter));
       });
     }
 }

Funktsiyani faqat ismim bilan filtrlay olaman, Mening savolim: ism, administrator, mamlakat, shahar idorasidan tashqari filtrlash mumkin, misol uchun agar siz 4 o'zgaruvchiga o'tishni qaytarsangiz:

{id: 3, ism: "Yangi kompaniya", o'tilganlik sanasi: "Admin 4"}

yoki iLl-ni qidirsam, qaytishi kerak:

{id: 4, ism: "Bepul kompaniya", o'tilganlik sanasi: "Jhon Miller", shahar: "Nyu-York"}

Rahmat

1
Bu JSON emas, bu ob'ektlar majmuasi. JSON JS ning pastki qismi kabi formatlangan ma'lumotlar almashinuvi formatidir. JSON-da formatlangan '[{"id": 1}, {"id": 2}}' mag'lubiyati . Semantika kabi ko'rinishi mumkin, lekin bu muhim farq.
qo'shib qo'ydi muallif Useless Code, manba
Bu JSON emas, bu ob'ektlar majmuasi. JSON JS ning pastki qismi kabi formatlangan ma'lumotlar almashinuvi formatidir. JSON-da formatlangan '[{"id": 1}, {"id": 2}}' mag'lubiyati . Semantika kabi ko'rinishi mumkin, lekin bu muhim farq.
qo'shib qo'ydi muallif Useless Code, manba

6 javoblar

Quyidagi qidirish funktsiyasi mos keluvchi moslamalarni < filter() dan foydalanadi. kodi> matnni qidirish. Ob'ektni qidirish uchun matn uchun mos kelmasligini aniqlash uchun ba'zi bir to'plamdagi har bir ob'ektning barcha qiymatlariga qarshi (). some() usuli text pastki qavatli shaklidan ob'ektga tushadigan qiymatlarning har biriga pastki qatlamli shaklda tekshiradi. : //lodash.com/docs/4.17.4#includes "rel =" nofollow noreferrer "> o'z ichiga oladi() .

Note that I used toLower(), as opposed to lowerCase() since the latter converts a string into their lower-case format as separated words while the former completely converts the entire string regardless of the string's case-format -- you can choose to switch it otherwise, depending on your requirements.

Update: I added an exclude parameter as a way to omit() certain properties when testing object values from the searched text.

function searchByText(collection, text, exclude) {
  text = _.toLower(text);
  return _.filter(collection, function(object) {
    return _(object).omit(exclude).some(function(string) {
      return _(string).toLower().includes(text);
    });
  });
}
console.log(searchByText(companies, '4'));
console.log(searchByText(companies, 'iLl'));
console.log(searchByText(companies, '4', ['id']));

<div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false"> <div class="snippet-code snippet-currently-hidden">

var companies = [{
    id: 1,
    name: "Test Company",
    admin: "Test Admin"
  },
  {
    id: 2,
    name: "Another Company",
    admin: "Test Admin",
    country: 'Spain'
  },
  {
    id: 3,
    name: "New Company",
    admin: "Admin 4"
  },
  {
    id: 4,
    name: "Free Company",
    admin: "Jhon Miller",
    city: 'New York'
  }
];

function searchByText(collection, text, exclude) {
  text = _.toLower(text);
  return _.filter(collection, function(object) {
    return _(object).omit(exclude).some(function(string) {
      return _(string).toLower().includes(text);
    });
  });
}

console.log(searchByText(companies, '4'));
console.log(searchByText(companies, 'iLl'));
console.log(searchByText(companies, '4', ['id']));
body > div { min-height: 100%; top: 0; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>
</div> </div>

Here's a compositional version of the solution above using partial() and flow()

function searchByText(collection, text, exclude) {
  return _.filter(collection, _.flow(
    _.partial(_.omit, _, exclude),
    _.partial(
      _.some, _,
      _.flow(_.toLower, _.partial(_.includes, _, _.toLower(text), 0))
    )
  ));
}

console.log(searchByText(companies, '4'));
console.log(searchByText(companies, 'iLl'));
console.log(searchByText(companies, '4', ['id']));

<div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false"> <div class="snippet-code snippet-currently-hidden">

var companies = [{
    id: 1,
    name: "Test Company",
    admin: "Test Admin"
  },
  {
    id: 2,
    name: "Another Company",
    admin: "Test Admin",
    country: 'Spain'
  },
  {
    id: 3,
    name: "New Company",
    admin: "Admin 4"
  },
  {
    id: 4,
    name: "Free Company",
    admin: "Jhon Miller",
    city: 'New York'
  }
];

function searchByText(collection, text, exclude) {
  return _.filter(collection, _.flow(
    _.partial(_.omit, _, exclude),
    _.partial(
      _.some, _,
      _.flow(_.toLower, _.partial(_.includes, _, _.toLower(text), 0))
    )
  ));
}

console.log(searchByText(companies, '4'));
console.log(searchByText(companies, 'iLl'));
console.log(searchByText(companies, '4', ['id']));
body > div { min-height: 100%; top: 0; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>
</div> </div>
0
qo'shib qo'ydi
@ Vivianita21 yangilanishimni tekshirib ko'radi.
qo'shib qo'ydi muallif ryeballar, manba
Yuqoridagi kod jsfiddle da jsfiddle.net/W4QfJ/13260
qo'shib qo'ydi muallif Ananda, manba
Rahmat sizga @ rieballar. Sizning 2 echimingiz juda oqilona, ​​lekin filtrni qanday qilib tashlashni bilishim kerak? chunki men 4 ta shou-2 ro'yxatga olsam va faqat 1ni ko'rsataman: {id: 3, ism: "New Company", admin: "Admin 4"},
qo'shib qo'ydi muallif Vivianita21, manba
Rahmat! Qaroringiz 100% to'g'ri.
qo'shib qo'ydi muallif Vivianita21, manba

Object.keys() is the key ;)

Buni ko'ring:

<div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code">

var companies= [
    { id: 1, name: "Test Company", admin: "Test Admin" },
    { id: 2, name: "Another Company", admin: "Test Admin", country: 'Spain' },
    { id: 3, name: "New Company", admin: "Admin 4" },
    { id: 4, name: "Free Company", admin: "Jhon Miller", city: 'New York' }
];

function searchBooks(filter){
    var result;
      if (typeof filter=== "undefined" ||  filter.length==0) {
          result = companies;
      } else {
        result = _.filter(companies, function (c) {

        //This part will transform every property value in a single string.
         var searchIn = Object.keys(c).reduce(function(res, val) { return (val !== 'id')?res+c[val]:res }, '');
         return _.includes(_.lowerCase(searchIn),_.lowerCase(filter));
       });
     }
     console.log(result)
 }
<script src="https://cdn.jsdelivr.net/lodash/4.17.4/lodash.min.js"></script>
<input type="text" onKeyUp="searchBooks(this.value)">
</div> </div>
0
qo'shib qo'ydi
Yangilanishimni tekshiring va menga nima kerakligini ayting.
qo'shib qo'ydi muallif Steeve Pitis, manba
Oh o'ylaymanki, siz qidirish kalitidan "id" kalitini olib tashlamoqchimisiz?
qo'shib qo'ydi muallif Steeve Pitis, manba
Men siz xohlagan narsani tushunishingizga shubham yo'q. Natijada id kodi bilan X (2, exemple) uchun barcha natijalarni ko'rsatishni xohlaysizmi?
qo'shib qo'ydi muallif Steeve Pitis, manba
Faqat birinchi natijani ko'rsatishni istasangiz, u holda return result [0] kerak
qo'shib qo'ydi muallif Steeve Pitis, manba
Sizga @SteevePitis uchun rahmat, sizning yechimingiz to'g'ri, lekin men filtr uchun kimligini qanday qilib tashlashim mumkinligini bilishim kerak, chunki men 4 ta 2-reliz yozishni yozsam va 1 nafari ko'rsataman.
qo'shib qo'ydi muallif Vivianita21, manba
Buni bilaman, lekin mening savolim agar siz qo'ng'iroq qilsangiz idni tashlashi mumkin. Boshqa reestrda "4" borligini tasavvur qiling, 2-sonli ro'yxatdan o'tkazishni qaytarish kerak. Rahmat
qo'shib qo'ydi muallif Vivianita21, manba

Object.keys() is the key ;)

Buni ko'ring:

<div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code">

var companies= [
    { id: 1, name: "Test Company", admin: "Test Admin" },
    { id: 2, name: "Another Company", admin: "Test Admin", country: 'Spain' },
    { id: 3, name: "New Company", admin: "Admin 4" },
    { id: 4, name: "Free Company", admin: "Jhon Miller", city: 'New York' }
];

function searchBooks(filter){
    var result;
      if (typeof filter=== "undefined" ||  filter.length==0) {
          result = companies;
      } else {
        result = _.filter(companies, function (c) {

        //This part will transform every property value in a single string.
         var searchIn = Object.keys(c).reduce(function(res, val) { return (val !== 'id')?res+c[val]:res }, '');
         return _.includes(_.lowerCase(searchIn),_.lowerCase(filter));
       });
     }
     console.log(result)
 }
<script src="https://cdn.jsdelivr.net/lodash/4.17.4/lodash.min.js"></script>
<input type="text" onKeyUp="searchBooks(this.value)">
</div> </div>
0
qo'shib qo'ydi
Yangilanishimni tekshiring va menga nima kerakligini ayting.
qo'shib qo'ydi muallif Steeve Pitis, manba
Oh o'ylaymanki, siz qidirish kalitidan "id" kalitini olib tashlamoqchimisiz?
qo'shib qo'ydi muallif Steeve Pitis, manba
Men siz xohlagan narsani tushunishingizga shubham yo'q. Natijada id kodi bilan X (2, exemple) uchun barcha natijalarni ko'rsatishni xohlaysizmi?
qo'shib qo'ydi muallif Steeve Pitis, manba
Faqat birinchi natijani ko'rsatishni istasangiz, u holda return result [0] kerak
qo'shib qo'ydi muallif Steeve Pitis, manba
Sizga @SteevePitis uchun rahmat, sizning yechimingiz to'g'ri, lekin men filtr uchun kimligini qanday qilib tashlashim mumkinligini bilishim kerak, chunki men 4 ta 2-reliz yozishni yozsam va 1 nafari ko'rsataman.
qo'shib qo'ydi muallif Vivianita21, manba
Buni bilaman, lekin mening savolim agar siz qo'ng'iroq qilsangiz idni tashlashi mumkin. Boshqa reestrda "4" borligini tasavvur qiling, 2-sonli ro'yxatdan o'tkazishni qaytarish kerak. Rahmat
qo'shib qo'ydi muallif Vivianita21, manba

How could search on every property with the same way, specifying your potential searching keys, see searchBooksSpecificProperties

Alternative, if you always want to search on all the fields you can get the keys on every item with _.keys(), see searchBooks

<div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code">

var companies= [
    { id: 1, name: "Test Company", admin: "Test Admin" },
    { id: 2, name: "Another Company", admin: "Test Admin", country: 'Spain' },
    { id: 3, name: "New Company", admin: "Admin 4" },
    { id: 4, name: "Free Company", admin: "Jhon Miller", city: 'New York' }
];

function searchBooks(companies, filter){
  var result;
    if (typeof filter=== "undefined" ||  filter.length==0) {
        result = companies;
    } else {
      result = _.filter(companies, function (c) {
        var cProperties = _.keys(c);
        _.pull(cProperties, 'id');
        return _.find(cProperties, function(property) {
          if (c[property]) {
            return _.includes(_.lowerCase(c[property]),_.lowerCase(filter));
          }          
        });         
     });
   }
   return result;
 }

 console.log('searchBooks:');
 console.log(searchBooks(companies, 'Admin 4'))
 console.log(searchBooks(companies, 'York'))
 
function searchBooksSpecificProperties(properties, companies, filter){
  var searchSpecificProperties = _.isArray(properties);
  var result;
    if (typeof filter=== "undefined" ||  filter.length==0) {
        result = companies;
    } else {
      result = _.filter(companies, function (c) {
        var cProperties = searchSpecificProperties ? properties : _.keys(c);
        return _.find(cProperties, function(property) {
          if (c[property]) {
            return _.includes(_.lowerCase(c[property]),_.lowerCase(filter));
          }          
        });         
     });
   }
   return result;
 }
 console.log('searchBooksSpecificProperties:');
 console.log(searchBooksSpecificProperties(['name', 'admin'], companies, 'Admin 4'))
 console.log(searchBooksSpecificProperties(['name', 'admin'], companies, 'York'))
<script src="https://cdn.jsdelivr.net/lodash/4.17.4/lodash.min.js"></script>
</div> </div>
0
qo'shib qo'ydi
Javobni o'zgartirib, 2 xil funksiyani qo'shdim. Siz searchBooks() va searchBooksSpecificProperties()
qo'shib qo'ydi muallif Apostolidis, manba
Rahmat @Apostolidis, lekin qanday qilib uni 2 parametrni ishga soladigan funktsiyani bajarishim mumkin? , xususiyatlari yo'q
qo'shib qo'ydi muallif Vivianita21, manba

How could search on every property with the same way, specifying your potential searching keys, see searchBooksSpecificProperties

Alternative, if you always want to search on all the fields you can get the keys on every item with _.keys(), see searchBooks

<div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code">

var companies= [
    { id: 1, name: "Test Company", admin: "Test Admin" },
    { id: 2, name: "Another Company", admin: "Test Admin", country: 'Spain' },
    { id: 3, name: "New Company", admin: "Admin 4" },
    { id: 4, name: "Free Company", admin: "Jhon Miller", city: 'New York' }
];

function searchBooks(companies, filter){
  var result;
    if (typeof filter=== "undefined" ||  filter.length==0) {
        result = companies;
    } else {
      result = _.filter(companies, function (c) {
        var cProperties = _.keys(c);
        _.pull(cProperties, 'id');
        return _.find(cProperties, function(property) {
          if (c[property]) {
            return _.includes(_.lowerCase(c[property]),_.lowerCase(filter));
          }          
        });         
     });
   }
   return result;
 }

 console.log('searchBooks:');
 console.log(searchBooks(companies, 'Admin 4'))
 console.log(searchBooks(companies, 'York'))
 
function searchBooksSpecificProperties(properties, companies, filter){
  var searchSpecificProperties = _.isArray(properties);
  var result;
    if (typeof filter=== "undefined" ||  filter.length==0) {
        result = companies;
    } else {
      result = _.filter(companies, function (c) {
        var cProperties = searchSpecificProperties ? properties : _.keys(c);
        return _.find(cProperties, function(property) {
          if (c[property]) {
            return _.includes(_.lowerCase(c[property]),_.lowerCase(filter));
          }          
        });         
     });
   }
   return result;
 }
 console.log('searchBooksSpecificProperties:');
 console.log(searchBooksSpecificProperties(['name', 'admin'], companies, 'Admin 4'))
 console.log(searchBooksSpecificProperties(['name', 'admin'], companies, 'York'))
<script src="https://cdn.jsdelivr.net/lodash/4.17.4/lodash.min.js"></script>
</div> </div>
0
qo'shib qo'ydi
Javobni o'zgartirib, 2 xil funksiyani qo'shdim. Siz searchBooks() va searchBooksSpecificProperties()
qo'shib qo'ydi muallif Apostolidis, manba
Rahmat @Apostolidis, lekin qanday qilib uni 2 parametrni ishga soladigan funktsiyani bajarishim mumkin? , xususiyatlari yo'q
qo'shib qo'ydi muallif Vivianita21, manba

How could search on every property with the same way, specifying your potential searching keys, see searchBooksSpecificProperties

Alternative, if you always want to search on all the fields you can get the keys on every item with _.keys(), see searchBooks

<div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code">

var companies= [
    { id: 1, name: "Test Company", admin: "Test Admin" },
    { id: 2, name: "Another Company", admin: "Test Admin", country: 'Spain' },
    { id: 3, name: "New Company", admin: "Admin 4" },
    { id: 4, name: "Free Company", admin: "Jhon Miller", city: 'New York' }
];

function searchBooks(companies, filter){
  var result;
    if (typeof filter=== "undefined" ||  filter.length==0) {
        result = companies;
    } else {
      result = _.filter(companies, function (c) {
        var cProperties = _.keys(c);
        _.pull(cProperties, 'id');
        return _.find(cProperties, function(property) {
          if (c[property]) {
            return _.includes(_.lowerCase(c[property]),_.lowerCase(filter));
          }          
        });         
     });
   }
   return result;
 }

 console.log('searchBooks:');
 console.log(searchBooks(companies, 'Admin 4'))
 console.log(searchBooks(companies, 'York'))
 
function searchBooksSpecificProperties(properties, companies, filter){
  var searchSpecificProperties = _.isArray(properties);
  var result;
    if (typeof filter=== "undefined" ||  filter.length==0) {
        result = companies;
    } else {
      result = _.filter(companies, function (c) {
        var cProperties = searchSpecificProperties ? properties : _.keys(c);
        return _.find(cProperties, function(property) {
          if (c[property]) {
            return _.includes(_.lowerCase(c[property]),_.lowerCase(filter));
          }          
        });         
     });
   }
   return result;
 }
 console.log('searchBooksSpecificProperties:');
 console.log(searchBooksSpecificProperties(['name', 'admin'], companies, 'Admin 4'))
 console.log(searchBooksSpecificProperties(['name', 'admin'], companies, 'York'))
<script src="https://cdn.jsdelivr.net/lodash/4.17.4/lodash.min.js"></script>
</div> </div>
0
qo'shib qo'ydi
Javobni o'zgartirib, 2 xil funksiyani qo'shdim. Siz searchBooks() va searchBooksSpecificProperties()
qo'shib qo'ydi muallif Apostolidis, manba
Rahmat @Apostolidis, lekin qanday qilib uni 2 parametrni ishga soladigan funktsiyani bajarishim mumkin? , xususiyatlari yo'q
qo'shib qo'ydi muallif Vivianita21, manba
Javascript UZB
Javascript UZB
99 ishtirokchilar

@js_uzb @vuejs_uz @react_uz @nodejs_uz @angular_uz @ngTashkent @yiiframework_uz @laravel_uz @linux_uzbek @python_uz @swift_uzb —————— @uzdevgroup @UzGeeksGroup ——— @UzDev_Jobs @jobs_uzb