-1

Basically I need some sort of library/set of functions that will allow me to perform advanced functions on arrays.

For example:

var jsondata = "SearchResponse":{ "Version":"2.0","Query":{ 
"SearchTerms":"sushi"},"Web":{ "Total":15000000,"Offset":0,"Results":[ 
{ "Title":"Sushi - Wikipedia, the free encyclopedia","Description":"In 
Japanese cuisine, sushi (寿司, 鮨, 鮓, sushi?) is vinegared rice, usually 
topped with other ingredients, including fish (cooked or uncooked) and 
vegetables.","Url":"http:\/\/en.wikipedia.org\/wiki\/Sushi","DisplayUrl
":"http:\/\/en.wikipedia.org\/wiki\/Sushi","DateTime":"2008-06-
09T06:42:34Z"}]}} /* pageview_candidate */}

var filterdata = filter(jsondata, {"Title":"Sushi - Wikipedia, the free encyclopedia"});

And then filterdata will contain all results in jsondata that have the Title Sushi - Wikipedia, the free encyclopedia

3 Answers 3

3

Take a look at underscore.js. You probably won’t be able to write code exactly as in your question, but it comes near to it:

_.filter(jsondata.Web.Results, function (val) {
    return val.Title === "Sushi - Wikipedia, the free encyclopedia";
});
Sign up to request clarification or add additional context in comments.

Comments

1

Well, first of all, jsondata is an Object, not an Array; however the jsondata.Web.Results property is an Array. With that in mind, you could make use of the JavaScript Array.filter method.

var results = jsondata.Web.Results.filter(function (value) { 
    // Return true if you want this 'value' object to appear in the 'results' Array.
    return (value.Title === "Sushi - Wikipedia, the free encyclopedia");
});

If you want to do more serious work with Arrays then it would be sensible to include a Collections Framework; the most popular one for JavaScript is underscore.js. A solid understanding of Collections will pay off dividends in the future for your programming career.

1 Comment

Note that the native filter method is not available in IE < 9, that’s why underscore.js implements it where not natively available.
1

Look at PHP.js. It brings PHP power to JavaScript.

1 Comment

I would definitely prefer the rather clean JavaScript API over PHP’s messed up library. Moreover, the native JavaScript filter is faster than any self-coded version.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.