Javascript在JSON对象中搜索

时间:2012-05-21 04:42:39

标签: javascript jquery jsonp json

我的应用程序中有一个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"}
]}

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

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

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

8 个答案:

答案 0 :(得分:34)

如果你的问题是,是否有一些内置的东西可以搜索你,那么不,没有。您基本上使用String#indexOfregular expression遍历数组以测试字符串。

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

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

  2. 在启用ES5的环境(或使用垫片)上Array#filter

  3. 因为您使用的是jQuery,jQuery.map

  4. 无聊的旧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;
    }
    

    您将obj.list称为source,将所需名称片段称为name

    或者,如果有空白条目或条目没有名称,请将if更改为:

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

    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;
    }
    

    再次,如果有空白条目的可能性(例如,undefined,而不是丢失; filter将跳过缺少条目),更改内部返回到:

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

    jQuery.map示例(此处我假设jQuery = $通常就是这种情况;如果您正在使用{$更改为jQuery {1}}):

    noConflict

    (如有必要,请再次添加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; } 。)

答案 1 :(得分:33)

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

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]);
    }
}

答案 2 :(得分:7)

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

例如:-

apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  annotations:
    nginx.ingress.kubernetes.io/ingress.class: nginx
    nginx.ingress.kubernetes.io/backend-protocol: "HTTPS"
    nginx.ingress.kubernetes.io/force-ssl-redirect: "true"
    nginx.ingress.kubernetes.io/rewrite-target: /
  name: dashboard-ingress
  namespace: kubernetes-dashboard
spec:
  rules:
  - host: dashboard.FQDN
    http:
      paths:
      - backend:
          serviceName: kubernetes-dashboard
          servicePort: 443
        path: /
  tls:
  - hosts:
    - dashboard.FQDN
    secretName: secret_dashboard
status:
  loadBalancer: {}

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

获取单个对象

      <el-table-column>
        <template
          slot="header">
          <el-popover
            ref="fromPopOver"
            placement="top-start"
            width="250"
            trigger="hover">
            <span>
             Tooltip info here
            </span>
          </el-popover>
          <span>Destination <i
            v-popover:fromPopOver
            class="el-icon-info
            text-blue" />
          </span>
        </template>
        <template slot-scope="scope">
          <span>{{ scope.row.SomeData }}</span>
        </template>

获取单个数组对象

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"}
]}

答案 3 :(得分:1)

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

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

答案 4 :(得分:0)

我使用正则表达式来使用JSON。

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

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

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

接下来,您需要重建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

使用此信息,可以使用正则表达式过滤JSON对象以返回键,值和父对象链。

您可以在http://json.spiritway.co/

查看我创作的图书馆和代码

答案 5 :(得分:0)

如果您在应用程序中的多个位置执行此操作,则使用客户端JSON数据库是有意义的,因为创建由array.filter()调用的自定义搜索函数比其他选项更加混乱且难以维护

查看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"}
]
*/

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

答案 6 :(得分:0)

我一直喜欢使用使代码易于维护的库。现在,我们将object-scan用于大多数数据处理,这确实有帮助。一旦你把头缠住了。这是解决问题的方法

const objectScan = require('object-scan');

const search = (haystack, k, v) => objectScan([`list[*].${k}`], {
  rtn: 'parent',
  filterFn: ({ value }) => value === v
})(haystack);

const obj = {
  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' }
  ]
};

console.log(search(obj, 'name', 'my Name'));
// => [ { name: 'my Name', id: 12, type: 'car owner' } ]

答案 7 :(得分:-2)

你可以试试这个:

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'));