Okky
Okky

Reputation: 10466

Search and find numbers starting with particular number

I was trying to create a search plugin for my custom table plugin.

In my search I use

function getObjects(obj, key, val, path) {
    for (var prop in obj) {
        if (prop == key && obj[key].toLowerCase().match(val)) {
            result.push(passName);
            matchFlag = 1;
        }
    }
}

where

This works as long as the search keyword is a string/character.

How to handle scenario where search keyword is numeric? I tried using indexOf also.

Upvotes: 1

Views: 70

Answers (3)

Hakan Bilgin
Hakan Bilgin

Reputation: 1122

You can use this javascript library; DefiantJS (defiantjs.com) which extends the global object JSON with the method "search". Using this method, you can search a JSON structure with XPath expressions like this:

var data = [
       {
          "name": "Tom",
          "age": 27
       },
       {
          "name": "Lisa",
          "age": 22
       }
    ],
    res1 = JSON.search( data, '//*[name = "Lisa"]' ),
    res2 = JSON.search( data, '//*[age = 27]' ),
    res3 = JSON.search( data, '//name[contains(.,"om")]/..' );

console.log( res1[0].age );
// 22

console.log( res2[0].name );
// Tom

console.log( res3[0] );
// { "name": "Tom", "age": 27 }

Here is a working fiddle:
http://jsfiddle.net/hbi99/2C8Ac/

Upvotes: 0

Okky
Okky

Reputation: 10466

The issue was from json, fixed it by adding toString()

function getObjects(obj, key, val, path) {
    for (var prop in obj) {
        if (prop == key && obj[key].toString().toLowerCase().match(val)) {
            result.push(passName);
            matchFlag = 1;
        }
    }
}

Upvotes: 1

Kevin Bowersox
Kevin Bowersox

Reputation: 94469

Just make the value a String by concatenating an empty String:

function getObjects(obj, key, val, path) {
    var value = val + "";
    for (var prop in obj) {
        if (prop == key && obj[key].toLowerCase().match(value)) {
            result.push(passName);
            matchFlag = 1;
        }
    }
}

Upvotes: 2

Related Questions