javascriptjsonlinq.js

linq.js unexpected results


Okay, so I have got this JSON object called "Faults"

"Faults":[{"RoomId":1,"ElementId":173,"FaultTypeId":1,"Count":1,"Remark":""},{"RoomId":3,"ElementId":211,"FaultTypeId":7,"Count":1,"Remark":""},{"RoomId":4,"ElementId":173,"FaultTypeId":1,"Count":1,"Remark":""}]

Faults object shown in debugger:

faults shown in debugger

Now I need to check if a room contains a Fault by using he RoomId. The code I'm using for this is:

    Enumerable.From(audit.Rooms).ForEach(function(room, index) {//√
    var containsFaults = '';

    //room.Id is ALWAYS filled, it can't be null
    var test1 = faults.Select("$.RoomId==" + room.Id).Count();
    var test2 = faults.Select("$.RoomId==" + room.Id);

    if (faults.Select("$.RoomId==" + room.Id).Count() > 0) {
        containsFaults = '√';
    }

But when I'm executing this code im getting the following results...

result printscreen

Why won't it just return the fault's from my object with the matching RoomId? I'm sure the Id's do match. What am I doing wrong here, i'm getting really stuck over this...

Thanks in advance!


Solution

  • To answer the question

    Why won't it just return the fault's from my object with the matching RoomId? I'm sure the Id's do match. What am I doing wrong here, i'm getting really stuck over this...

    You need to add .ToArray() to render the result.

    var test2 = faults.Select("$.RoomId==" + room.Id).ToArray();
    //                                               ^^^^^^^^^^
    

    var audit = { Faults: [{ RoomId: 42, ElementId: 4711, FaultTypeId: 0, Count: 0, Remark: "no fault" }, { RoomId: 1, ElementId: 173, FaultTypeId: 1, Count: 1, Remark: "" }, { RoomId: 3, ElementId: 211, FaultTypeId: 7, Count: 1, Remark: "" }, { RoomId: 4, ElementId: 173, FaultTypeId: 1, Count: 1, Remark: "" }] },
        roomId = 4,
        dataset = Enumerable.From(audit.Faults),
        test1 = dataset.Where("$.Count > 0 && $.RoomId==" + roomId).Count();
        test2 = dataset.Where("$.Count > 0 && $.RoomId==" + roomId).ToArray();
    
    console.log(test1);
    console.log(test2);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/linq.js/2.2.0.2/linq.js"></script>