过滤任何属性包含值的对象数组

新手上路,请多包涵

我想知道根据 string keyword 过滤对象数组的最干净、更好的方法是什么。必须在对象的任何属性中进行搜索。

当我键入 lea 我想遍历所有对象及其所有属性以返回包含 lea 的对象

当我键入 italy 时,我想遍历所有对象及其所有属性以返回包含 italy 的对象。

我知道有很多解决方案,但到目前为止,我只看到了一些您需要指定要匹配的属性的解决方案。

欢迎使用 ES6 和 lodash!

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

    filterByValue(arrayOfObject, 'lea')   // => [{name: 'Lea',country: 'Italy'}]
    filterByValue(arrayOfObject, 'ita')   // => [{name: 'Lea',country: 'Italy'}, {name: 'John',country: 'Italy'}]

原文由 Léo Coco 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 346
2 个回答

您可以对其进行过滤并仅搜索一次出现的搜索字符串。

使用方法:

 function filterByValue(array, string) {
    return array.filter(o =>
        Object.keys(o).some(k => o[k].toLowerCase().includes(string.toLowerCase())));
}

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

console.log(filterByValue(arrayOfObject, 'lea')); // [{name: 'Lea', country: 'Italy'}]
console.log(filterByValue(arrayOfObject, 'ita')); // [{name: 'Lea', country: 'Italy'}, {name: 'John', country: 'Italy'}]
 .as-console-wrapper { max-height: 100% !important; top: 0; }

原文由 Nina Scholz 发布,翻译遵循 CC BY-SA 3.0 许可协议

好吧,当我们已经知道它不会使用方法搜索对象时,我们可以执行以下操作以节省时间复杂度:

 function filterByValue(array, value) {
  return array.filter((data) =>  JSON.stringify(data).toLowerCase().indexOf(value.toLowerCase()) !== -1);
}

原文由 binariedMe 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题