Search code examples
javascriptjqueryjsonsearchyodlee

Searching JSON resultset using keywords and return only matches


I am trying to search the below Yodlee JSON datafeed for example if keyword is "furniture" then only display "plainTextDescription" which equals to "furniture transactions"

Not quite sure how to grep through nested JSON resultsets using JQuery...

///RAW YODLEE JSON RESULTSET

http://pastebin.com/6498mZJf

Thanks in advance!


Solution

  • Here's the Fiddle.

    The short version is this:

    var data = JSON.stringify({ "Body": [{...my obscenely long JSON}] });
    var parsedData = JSON.parse(data);
    var transactions = [];
    
    // processes account objects
    function processAccount(account) {
        if (account.cardTransactions) {
            for (var i = 0; i < account.cardTransactions.length; i++) {
                var transaction = account.cardTransactions[i];
                if (transaction) {
                    if (transaction.categorizationKeyword.toLowerCase() === 'shell oil') {
                        transactions.push(transaction);
                    }
                }
            }
        }
    }
    
    // processes the itemData objects
    function processItemData(itemData) {
        for (var i = 0; i < itemData.accounts.length; i++) {
            processAccount(itemData.accounts[i]);
        }
    }
    
    (function() {
        // iterates through elements in the body
        for (var i = 0; i < parsedData.Body.length; i++) {
            processItemData(parsedData.Body[i].itemData);
        }
    
        for (var j = 0; j < transactions.length; j++) {
            $('#container').append('<p>' + transactions[j].plainTextDescription + '</p>');
        }
    })();
    

    I broke the bits into multiple functions for easier reading, but one could re-factor it to be less verbose.