2017-08-07 116 views
1

我想通過關鍵字專門搜索JSON。我已經成功搜索了一個ID,該ID在下面的代碼中是「tags」。不過,我想要做的是,在「標籤」的ID中搜索,但是通過「折舊」的關鍵字搜索。只有JSON中的括號表示「折舊」纔會被選中。然後,標題和uri將被從中拉出並寫入文檔,就像我在代碼中一樣。通過關鍵字搜索JSON與jQuery

我該如何去關於使用當前代碼進行關鍵字搜索?如果我的邏輯很難理解,請在評論中告訴我。在此先感謝:)

注意:這正是數據將被使用的JSON格式。

這裏是我的代碼:

<script type='text/javascript'> 
    window.onload=function(){ 
    var data = { 
     "Feed": [ 
      { 
       "categories":[ 
       "Depreciated", 
       "Test" 
       ], 
       "content":"", 
       "tags":[ 
       "Depreciated", 
       "Test" 
       ], 
       "title":"Visual Design", 
       "uri":"google.com" 
      }, 
      { 
       "categories":[ 
       "Depreciated" 
       ], 
       "content":"", 
       "tags":[ 
       "Depreciated" 
       ], 
       "title":"Typography", 
       "uri":"google.com" 
      } 
     ] 
     }, 
     res = JSON.search(data, '//*[tags]'); 

    for (var i=0, str=''; i<res.length; i++) { 
     str += '<a href="' + res[i].uri + '">Link</a>' + res[i].title + '<br/>'; 
    } 

    document.getElementById('output').innerHTML = str; 
    } 
</script> 
+0

不知道爲什麼有人向下投你的問題,這是一個非常好的問題。 – Difster

+0

謝謝!可能是因爲我不是「專業人員」:P – rniller

+0

您可以迭代您的json對象並測試您想要的任何內容。 https://stackoverflow.com/questions/684672/how-do-i-loop-through-or-enumerate-a-javascript-object – Difster

回答

1

有沒有必要使用jQuery這一點。 Try something like this instead

function getTitlesByTag(arr, tag) { 
    return arr.filter(function(item) { 
    return item.tags.includes(tag) 
    }).map(function(item) { 
    return return { 
     title: item.title, 
     uri: item.uri 
    } 
    }) 
} 

Array.prototype.includes沒有IE瀏覽器的支持,所以,如果你擔心,你可以換的是檢查出的indexOf像這樣:

function getTitlesByTag(arr, tag) { 
    return arr.filter(function(item) { 
    return item.tags.includes(tag) 
    }).map(function(item) { 
    return { 
     title: item.title, 
     uri: item.uri 
    } 
    }) 
} 
+0

shadymoses,謝謝你的代碼walk-thru和例子。這很有幫助!試圖理解你的代碼和Will's - 你的方法,是將JSON分解成一個更容易理解的數組,然後將它放入要訪問的函數中? – rniller

+0

是的。您要查找的相關數據是一個數組,因此如果您始終可以依賴該結構,那麼您可以直接指向它。使用數組非常方便。如果代碼不需要抽象,則不必具有單獨的函數。 – shadymoses

1

shadeymoses比我快,但本質上你只需要filter()map()

var data = { 
 
    "Feed": [{ 
 
     "categories": [ 
 
     "Depreciated", 
 
     "Test" 
 
     ], 
 
     "content": "", 
 
     "tags": [ 
 
     "Depreciated", 
 
     "Test" 
 
     ], 
 
     "title": "Visual Design", 
 
     "uri": "google.com" 
 
    }, 
 
    { 
 
     "categories": [ 
 
     "Depreciated" 
 
     ], 
 
     "content": "", 
 
     "tags": [ 
 
     "Depreciated" 
 
     ], 
 
     "title": "Typography", 
 
     "uri": "google.com" 
 
    } 
 
    ] 
 
}; 
 

 
let results = data.Feed.filter(el => el.tags.includes('Depreciated')).map(el => ({ 
 
    uri: el.uri, 
 
    title: el.title 
 
})); 
 

 
console.log(results);

+0

謝謝!這也很有幫助。過濾器很有意義。據我瞭解,一個過濾器會將數據分離成一個變量的卡盤? – rniller

+1

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter它遍歷數組並返回一個(通常較小的 )數組。 – Will

+0

對於返回null有什麼想法? – rniller