使用lodash.js

时间:2017-02-20 13:55:02

标签: javascript json lodash

朋友我有对象json:

  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' }
];

我正在编写一个返回new json的函数,其中包含我作为参数传递的元素(filter)。我做了一个简单的

   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));
       });
     }
 }

使用我的功能我只能按名称进行过滤,我的问题是:我如何按名称,管理员,国家,城市进行过滤除了id,例如,如果你在变量中传递4应返回:

{id:3,姓名:"新公司",管理员:"管理员4" }

或者如果我搜索iLl应该返回:

{id:4,姓名:"自由公司",管理员:" Jhon Miller",城市:'纽约' }

由于

3 个答案:

答案 0 :(得分:0)

如何以相同的方式搜索每个媒体资源,指定您的潜在搜索键,请参阅searchBooksSpecificProperties

或者,如果您始终要搜索所有字段,则可以使用_.keys()获取每个项目的键,请参阅searchBooks

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>

答案 1 :(得分:0)

Object.keys()是关键;)

试试这个:

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)">

答案 2 :(得分:0)

下面的搜索功能使用filter()text搜索中获取匹配的对象。要确定某个对象是否与搜索的text匹配,我们会对集合中每个对象的所有值使用some()some()方法使用includes()针对搜索的text的低层表单,以较低的形式测试对象中的每个值。

请注意,我使用toLower()而不是lowerCase(),因为后者将字符串转换为小写格式作为单独的单词,而前者完全转换整个字符串而不管字符串&#39 ; s格式 - 您可以选择以其他方式切换,具体取决于您的要求。

更新:我在测试搜索到的text中的对象值时添加了排除参数作为omit()某些属性的方法。

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']));

&#13;
&#13;
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']));
&#13;
body > div { min-height: 100%; top: 0; }
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>
&#13;
&#13;
&#13;

以上是使用partial()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']));

&#13;
&#13;
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']));
&#13;
body > div { min-height: 100%; top: 0; }
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>
&#13;
&#13;
&#13;