JSON 对象内的 Javascript 搜索

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10679580/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 02:28:23  来源:igfitidea点击:

Javascript search inside a JSON object

javascriptjqueryjsonpjson

提问by ramesh

I had a JSON string / object in my application.

我的应用程序中有一个 JSON 字符串/对象。

{"list": [
    {"name":"my Name","id":12,"type":"car owner"},
    {"name":"my Name2","id":13,"type":"car owner2"},
    {"name":"my Name4","id":14,"type":"car owner3"},
    {"name":"my Name4","id":15,"type":"car owner5"}
]}

I had a filter box in my application, and when I type a name into that box, we have to filter the object and display the result.

我的应用程序中有一个过滤器框,当我在该框中输入名称时,我们必须过滤对象并显示结果。

For example, if the user types "name" and hits search, then we have to search full names in the JSON object and return the array, just like a MySQL search ...

例如,如果用户键入“name”并点击搜索,那么我们必须在 JSON 对象中搜索全名并返回数组,就像 MySQL 搜索一样......

My question is to filter the json object with string and return the array....

我的问题是用字符串过滤json对象并返回数组....

回答by McGarnagle

You could just loop through the array and find the matches:

您可以循环遍历数组并找到匹配项:

var results = [];
var searchField = "name";
var searchVal = "my Name";
for (var i=0 ; i < obj.list.length ; i++)
{
    if (obj.list[i][searchField] == searchVal) {
        results.push(obj.list[i]);
    }
}

回答by T.J. Crowder

If your question is, is there some built-in thing that will do the search for you, then no, there isn't. You basically loop through the array using either String#indexOfor a regular expressionto test the strings.

如果您的问题是,是否有一些内置的东西可以为您进行搜索,那么不,没有。您基本上使用正则表达式String#indexOf正则表达式遍历数组来测试字符串。

For the loop, you have at least three choices:

对于循环,您至少有三个选择:

  1. A boring old forloop.

  2. On ES5-enabled environments (or with a shim), Array#filter.

  3. Because you're using jQuery, jQuery.map.

  1. 一个无聊的老for循环。

  2. 在启用 ES5 的环境(或带有 shim)中,Array#filter.

  3. 由于您使用jQuery jQuery.map

Boring old forloop example:

无聊的旧for循环示例:

function search(source, name) {
    var results = [];
    var index;
    var entry;

    name = name.toUpperCase();
    for (index = 0; index < source.length; ++index) {
        entry = source[index];
        if (entry && entry.name && entry.name.toUpperCase().indexOf(name) !== -1) {
            results.push(entry);
        }
    }

    return results;
}

Where you'd call that with obj.listas sourceand the desired name fragment as name.

您可以使用obj.listassource和所需的名称片段作为name.

Or if there's any chance there are blank entries or entries without names, change the ifto:

或者,如果有可能出现空白条目或没有名称的条目,请将if其更改为:

        if (entry && entry.name && entry.name.toUpperCase().indexOf(name) !== -1) {

Array#filterexample:

Array#filter例子:

function search(source, name) {
    var results;

    name = name.toUpperCase();
    results = source.filter(function(entry) {
        return entry.name.toUpperCase().indexOf(name) !== -1;
    });
    return results;
}

And again, if any chance that there are blank entries (e.g., undefined, as opposed to missing; filterwill skip missingentries), change the inner return to:

再一次,如果有任何机会出现空白条目(例如,undefined与丢失相反;filter将跳过丢失的条目),将内部返回更改为:

        return entry && entry.name && entry.name.toUpperCase().indexOf(name) !== -1;

jQuery.mapexample (here I'm assuming jQuery= $as is usually the case; change $to jQueryif you're using noConflict):

jQuery.map示例(这里我假设jQuery=$通常是这种情况;如果您正在使用,请更改$为):jQuerynoConflict

function search(source, name) {
    var results;

    name = name.toUpperCase();
    results = $.map(source, function(entry) {
        var match = entry.name.toUpperCase().indexOf(name) !== -1;
        return match ? entry : null;
    });
    return results;
}

(And again, add entry && entry.name &&in there if necessary.)

(再次,entry && entry.name &&如有必要,在那里添加。)

回答by Anand Deep Singh

You can simply save your data in a variable and use find(to get single object of records) or filter(to get single array of records) method of JavaScript.

您可以简单地将数据保存在一个变量中,然后使用 JavaScript 的 find(获取单个记录对象)或 filter(获取单个记录数组)方法。

For example :-

例如 :-

let data = {
 "list": [
   {"name":"my Name","id":12,"type":"car owner"},
   {"name":"my Name2","id":13,"type":"car owner2"},
   {"name":"my Name4","id":14,"type":"car owner3"},
   {"name":"my Name4","id":15,"type":"car owner5"}
]}

and now use below command onkeyup or enter

现在使用下面的命令 onkeyup 或输入

to get single object

获取单个对象

data.list.find( record => record.name === "my Name")

to get single array object

获取单个数组对象

data.list.filter( record => record.name === "my Name")

回答by mikewhit

I adapted regex to work with JSON.

我调整了正则表达式以使用 JSON。

First, stringify the JSON object. Then, you need to store the starts and lengths of the matched substrings. For example:

首先,将 JSON 对象字符串化。然后,您需要存储匹配子字符串的开头和长度。例如:

"matched".search("ch") // yields 3

For a JSON string, this works exactly the same (unless you are searching explicitly for commas and curly brackets in which case I'd recommend some prior transform of your JSON object before performing regex (i.e. think :, {, }).

对于 JSON 字符串,这完全相同(除非您明确搜索逗号和大括号,在这种情况下,我建议您在执行正则表达式之前先对 JSON 对象进行一些转换(即认为:、{、})。

Next, you need to reconstruct the JSON object. The algorithm I authored does this by detecting JSON syntax by recursively going backwards from the match index. For instance, the pseudo code might look as follows:

接下来,您需要重建 JSON 对象。我编写的算法通过从匹配索引递归地返回来检测 JSON 语法来做到这一点。例如,伪代码可能如下所示:

find the next key preceding the match index, call this theKey
then find the number of all occurrences of this key preceding theKey, call this theNumber
using the number of occurrences of all keys with same name as theKey up to position of theKey, traverse the object until keys named theKey has been discovered theNumber times
return this object called parentChain

With this information, it is possible to use regex to filter a JSON object to return the key, the value, and the parent object chain.

有了这些信息,就可以使用正则表达式来过滤 JSON 对象以返回键、值和父对象链。

You can see the library and code I authored at http://json.spiritway.co/

您可以在http://json.spiritway.co/ 上查看我编写的库和代码

回答by HymaningLiu

Use PaulGuo's jSQL, a SQL like database using javascript. For example:

使用PaulGuojSQL,一个使用 javascript 的类似 SQL 的数据库。例如:

var db = new jSQL();
db.create('dbname', testListData).use('dbname');
var data = db.select('*').where(function(o) {
    return o.name == 'Hymaning';
}).listAll();

回答by Rob Evans

If you are doing this in more than one place in your application it would make sense to use a client-side JSON database because creating custom search functions that get called by array.filter() is messy and less maintainable than the alternative.

如果您在应用程序中的多个位置执行此操作,那么使用客户端 JSON 数据库是有意义的,因为创建由 array.filter() 调用的自定义搜索函数比替代方法更混乱且不易维护。

Check out ForerunnerDB which provides you with a very powerful client-side JSON database system and includes a very simple query language to help you do exactly what you are looking for:

查看 ForerunnerDB,它为您提供了一个非常强大的客户端 JSON 数据库系统,并包含一个非常简单的查询语言来帮助您准确地执行您正在寻找的操作:

// Create a new instance of ForerunnerDB and then ask for a database
var fdb = new ForerunnerDB(),
    db = fdb.db('myTestDatabase'),
    coll;

// Create our new collection (like a MySQL table) and change the default
// primary key from "_id" to "id"
coll = db.collection('myCollection', {primaryKey: 'id'});

// Insert our records into the collection
coll.insert([
    {"name":"my Name","id":12,"type":"car owner"},
    {"name":"my Name2","id":13,"type":"car owner2"},
    {"name":"my Name4","id":14,"type":"car owner3"},
    {"name":"my Name4","id":15,"type":"car owner5"}
]);

// Search the collection for the string "my nam" as a case insensitive
// regular expression - this search will match all records because every
// name field has the text "my Nam" in it
var searchResultArray = coll.find({
    name: /my nam/i
});

console.log(searchResultArray);

/* Outputs
[
    {"name":"my Name","id":12,"type":"car owner"},
    {"name":"my Name2","id":13,"type":"car owner2"},
    {"name":"my Name4","id":14,"type":"car owner3"},
    {"name":"my Name4","id":15,"type":"car owner5"}
]
*/

Disclaimer: I am the developer of ForerunnerDB.

免责声明:我是 ForerunnerDB 的开发者。

回答by Mengty Vong

You can try this:

你可以试试这个:

function search(data,search) {
    var obj = [], index=0;
    for(var i=0; i<data.length; i++) {
      for(key in data[i]){
         if(data[i][key].toString().toLowerCase().indexOf(search.toLowerCase())!=-1) {
                obj[index] = data[i];
                index++;
                break;
         }
     }
     return obj;
}
console.log(search(obj.list,'my Name'));