用Javascript在对象数组的属性中搜索字符串 [英] Javascript-searching for a string in the properties of an array of objects

查看:75
本文介绍了用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.

这篇关于用Javascript在对象数组的属性中搜索字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆