最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Search in all json's elements with lodash.js - Stack Overflow

programmeradmin7浏览0评论

friens i have object json :

  var panies= [
    { 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' }
];

and I am writing a function for return new json with elements that I pass as parameters(filter). I make a simple

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

With my function I can only filter by name, My question is: how i can filter by name,admin,country,city except by id, for example if you pass 4 in the variable should return :

{ id: 3, name: "New Company", admin: "Admin 4" }

or if I search iLl should return :

{ id: 4, name: "Free Company", admin: "Jhon Miller", city: 'New York' }

Thanks

friens i have object json :

  var panies= [
    { 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' }
];

and I am writing a function for return new json with elements that I pass as parameters(filter). I make a simple

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

With my function I can only filter by name, My question is: how i can filter by name,admin,country,city except by id, for example if you pass 4 in the variable should return :

{ id: 3, name: "New Company", admin: "Admin 4" }

or if I search iLl should return :

{ id: 4, name: "Free Company", admin: "Jhon Miller", city: 'New York' }

Thanks

Share Improve this question asked Feb 20, 2017 at 13:55 Vivianita21Vivianita21 571 silver badge6 bronze badges 1
  • That's not JSON, it's an array of objects. JSON is a data exchange format that is formatted like a subset of JS. The string '[{"id":1},{"id":2}]' is data formatted in JSON, it could be parsed into a JS array: [{id: 1}, {id: 2}]. It might seem like semantics, but it is an important distinction. – Useless Code Commented Feb 20, 2017 at 14:49
Add a ment  | 

3 Answers 3

Reset to default 5

The search function below makes use of filter() to get the matched objects from the text search. To determine if an object is a match for the searched text, we use some() against all values of each object in the collection. The some() method tests each of the values in the object in a lower-cased form against the lower-cased form of the searched text using includes().

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 pletely 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(panies, '4'));
console.log(searchByText(panies, 'iLl'));
console.log(searchByText(panies, '4', ['id']));

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

Here's a positional 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(panies, '4'));
console.log(searchByText(panies, 'iLl'));
console.log(searchByText(panies, '4', ['id']));

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

Object.keys() is the key ;)

Try this :

var panies= [
    { 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 = panies;
      } else {
        result = _.filter(panies, 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/lodash/4.17.4/lodash.min.js"></script>
<input type="text" onKeyUp="searchBooks(this.value)">

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

var panies= [
    { 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(panies, filter){
  var result;
    if (typeof filter=== "undefined" ||  filter.length==0) {
        result = panies;
    } else {
      result = _.filter(panies, 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(panies, 'Admin 4'))
 console.log(searchBooks(panies, 'York'))
 
function searchBooksSpecificProperties(properties, panies, filter){
  var searchSpecificProperties = _.isArray(properties);
  var result;
    if (typeof filter=== "undefined" ||  filter.length==0) {
        result = panies;
    } else {
      result = _.filter(panies, 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'], panies, 'Admin 4'))
 console.log(searchBooksSpecificProperties(['name', 'admin'], panies, 'York'))
<script src="https://cdn.jsdelivr/lodash/4.17.4/lodash.min.js"></script>

发布评论

评论列表(0)

  1. 暂无评论