在Json文件中搜索并使用Javascript

时间:2015-07-28 05:01:47

标签: javascript json

我正在通过Javascript开发FirefoxOS的字典应用程序。我的json文件看起来像这样

[
{"id":"3784","word":"Ajar","type":"adv.","descr":" Slightly turned or opened; as, the door was standing ajar.","track":"a","track_2":"Aj","track_3":"Aja"},
{"id":"3785","word":"Ajar","type":"adv.","descr":" In a state of discord; out of harmony; as, he is ajar with the world.","track":"a","track_2":"Aj","track_3":"Aja"},{"id":"3786","word":"Ajog","type":"adv.","descr":" On the jog.","track":"a","track_2":"Aj","track_3":"Ajo"},
{"id":"3787","word":"Ajutage","type":"n.","descr":" A tube through which water is discharged; an efflux tube; as, the ajutage of a fountain.","track":"a","track_2":"Aj","track_3":"Aju"}                               ]

现在我想查询这个json文件,其中word =" aj"并获得匹配结果的所有匹配结果或ID。我怎么能这样做?

3 个答案:

答案 0 :(得分:0)

尝试这个 UPDATED FIDDLE DEMO

var jsonArrr =[
{"id":"3784","word":"Ajar","type":"adv.","descr":" Slightly turned or opened; as, the door was standing ajar.","track":"a","track_2":"Aj","track_3":"Aja"},
{"id":"3785","word":"Ajar","type":"adv.","descr":" In a state of discord; out of harmony; as, he is ajar with the world.","track":"a","track_2":"Aj","track_3":"Aja"},{"id":"3786","word":"Ajog","type":"adv.","descr":" On the jog.","track":"a","track_2":"Aj","track_3":"Ajo"},
{"id":"3787","word":"Ajutage","type":"n.","descr":" A tube through which water is discharged; an efflux tube; as, the ajutage of a fountain.","track":"a","track_2":"Aj","track_3":"Aju"}                               ];

var matchMe = new RegExp('^' + 'aj', 'i');
    var matches = [];
        for (var i in jsonArrr) {
            if (jsonArrr[i].word.search(matchMe) > -1 ) {

                    matches.push( {'id': i, 'word': jsonArrr[i].word} );

            }
        }

查看结果

 for (var i in matches) { 
                console.log(matches[i].word);
                //your code
                }

检查元素中选择控制台窗口以查看结果

答案 1 :(得分:0)

var matchedIndexes = []
for (var i=0; i < array.length; i++) {
    var obj = array[i];
    if (obj.hasOwnProperty("word")) {
        if(obj["word"].match(/aj/i)) {
            console.log("matched");
            matchedIndexes.push(i);     
        }
    }
}

matchedIndexes将包含对象具有单词&#34; aj&#34;的所有索引。 (不区分大小写)。此代码中的array是数组的对象。

答案 2 :(得分:0)

循环遍历json数组:

var result = null;
    Objects.forEach(function(obj, i){
        if(obj.word == 'aj'){
            return result = obj;
        }
    });
    console.log(result);