用Javascript在对象数组的属性中搜索字符串

用Javascript在对象数组的属性中搜索字符串

问题描述:

我有一个JSON对象数组.给定一个搜索字符串,我只想过滤那些具有该字符串作为其属性之一的子字符串的对象的数组.如何有效地做到这一点?

I have an array of JSON objects. Given a search string, I want to filter the array for only those objects which have that string as a substring of one of their properties. How do I do this efficiently?

假设您要在属性 value 中找到子字符串,可以使用以下代码:

Assuming you want to find the substring in the property value, you can use the following code:

const arr = [
  {a:'abc', b:'efg', c:'hij'},
  {a:'abc', b:'efg', c:'hij'},
  {a:'123', b:'456', c:'789'},
];

const search = 'a';

const res = arr.filter(obj => Object.values(obj).some(val => val.includes(search)));

console.log(res);

如果要搜索属性 name ,请使用Object.keys而不是Object.values.

If you want to search the property name, use Object.keys instead of Object.values.

请注意,Object.values是ES2017的功能.

Please note that Object.values is a feature of ES2017.