Search code examples
javascriptunderscore.jslinq.js

where function of Linq.js on Json data not working


How to correct following code for desired output,

var Data = [{ "A": -27, "B": -39 }, { "A": 28, "B": 0}]

var filter = "x[A]==28";

var findItem = Enumerable.From(Data)
 .Where(function (x) { return filter ; })
 .ToArray();

alert(findItem.length);

$.each(findItem, function (i, value) {
alert(value["A"]);
});

It should give me one value A:28 or complete one record { "A": 28, "B": 0}, why i am getting two values, How to get correct results ?

using "linq.js" from following path: [ https://raw.github.com/gist/1175460/fb7404d46cab20e31601740ab8b35d99a584f941/linq.js ]

code at JSfiddle: http://jsfiddle.net/Irfanmunir/gLXNw/2/


Solution

  • You either have to pass a predicate function, or a string that represents such a function. You're passing a function, so linq.js doesn't expect another function/string.

    For Linq.js, you have to use this syntax for a string:

    var filter = "x => x['A']==28";  // also note the quotes surrounding A
    

    You then pass this function string to .Where:

    .Where(filter)
    

    You can of course also inline this:

    .Where("x => x['A']==28")
    

    http://jsfiddle.net/gLXNw/3/