简体   繁体   English

如何遍历 JSON Object 的数组以查找包含用户输入字符的属性值

[英]How can loop through array of JSON Object to find property value that includes user input characters

What is the correct method JavaScript function I can use to loop through an array of JSON data and return the JSON.KEY value that includes the user input query What is the correct method JavaScript function I can use to loop through an array of JSON data and return the JSON.KEY value that includes the user input query

Suppose that we have an array books with these data假设我们有一个包含这些数据的数组 books

const books = [
    { title: 'chemistry', pages: 123 },
    { title: 'chemical abcd', pages: 103 },
    { title: 'anatomy of something ', pages: 423 }
];

When a user query is当用户查询是

let  query= 'chemi'

Then the output should be那么 output 应该是

filteredBooks = [
    { title: 'chemistry', pages: 123 },
    { title: 'chemical abcd', pages: 103 }
];

For this I would use the js Array.filter method:为此,我将使用 js Array.filter方法:

const filteredBooks = books.filter(book => book.title.includes(query))

In addition of the other questions, using destructuring saves a bit of code:除了其他问题,使用解构可以节省一些代码:

const filteredBooks = books.filter(({title}) => title.includes(query));

this method searches all the values of the object if they contain the query.此方法搜索 object 的所有值(如果它们包含查询)。 you should make your query lowercase first:您应该首先将查询设为小写:

query=query.toLowerCase();
filteredBooks = books.filter(book=>Object.values(book).some(value=>value.toString().toLowerCase().includes(query)));

if the book object has sub-fields, this is a lazy way to query them:如果书 object 有子字段,这是一种懒惰的查询方式:

query=query.toLowerCase();
filteredBooks = books.filter(book=>JSON.stringify(Object.values(book)).toLowerCase().includes(query))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM