1

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/

3
  • You're returning a string, which is "truthy" (evaluates to true). You probably want to actually evaluate your filter in the where callback: .Where(function (x) { return x['A'] == 28; }) Commented Jan 8, 2013 at 18:10
  • It will not work as i am passing a variable field for where clause. The solution mention below works Commented Jan 9, 2013 at 12:03
  • Can you update the linq.js path. The path you have given is broken, So all the jsfiddle are not working. Commented Jan 25, 2022 at 11:59

2 Answers 2

3

your filter is a string which always evaluates to true. put your filter inside a function:

var filter = function(x) { return x['A'] === 28 };

and use this:

.Where(filter)

see updated fiddle: http://jsfiddle.net/gLXNw/4/

Sign up to request clarification or add additional context in comments.

2 Comments

i need x['A'] === 28 in a variable, so I can create and pass filter at runtime to where clause.
then it should be fine to use @pimvdb's solution
2

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/

3 Comments

i like your answer more ;-)
@hereandnow78 The syntax mirrors Linq syntax, but I wouldn't be surprised if there's a significant performance hit for doing this.
@Shmiddty: I don't know how it's implemented, but such a string only has to be parsed once, and the real generated function can be reused thereafter.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.