0

I am struggeling with this foor loop. I want to get the "customers" most recent order and store it in my database. But when I do this loop I get both the orders, the failed one and the recent one.

    for (var i = 0; i < json.length; i++) {

    var TestOrdersXML = <testOrders _key="@testOrderId" operation="insertOrUpdate"/>;

    if (json[i].testOrderId != undefined) TestOrdersXML.@testOrderId = json[i].testOrderId;
    if (json[i].customerId != undefined) TestOrdersXML.@customerId = json[i].customerId;
    if (json[i].status != undefined) TestOrdersXML.@status = json[i].status;
    if (json[i].installationOrderData.state != undefined) TestOrdersXML.@state = json[i].installationOrderData.state;


   logInfo("Status: " + json[i].status + " STATE: " + json[i].installationOrderData.state);
    //collection.appendChild(TestOrdersXML);
  }

The log:

Status: FAILED State: failed 
Stauts: SUCCESS State: BOOKED 

This is the array with two objects.

[
    {
        "installationOrderData":{
            "state": "booked"
        },
        "customerId": 123456,
        "testOrderId": 123456,
        "status": SUCCESS
    },
    {
        "installationOrderData":{
            "state": "failed"
        },
        "customerId": 123456,
        "testOrderId": 123456,
        "status": FAILED
    }
]

The question I am asking is, how do I only get the most recent object?

Thanks.

9
  • 1
    How do you know which is the most recent object? Dec 6, 2018 at 8:49
  • always the 0 in the array. Dec 6, 2018 at 8:49
  • 1
    Ok; have you tried json[0]? Dec 6, 2018 at 8:50
  • Most recent object based on what? Dec 6, 2018 at 8:51
  • No, you mean as the second statement in the loop? Dec 6, 2018 at 8:52

1 Answer 1

0

To get the first item / object in the array

To get the first item in the array use [0].

Arrays are 0 index based, so item at possition [0] will always be your first.

example:

let array = [1,2,3]
array[0] // 1
array[1] // 2
array[2] // 3

To stop the loop in the first item / object in array

simply add return; after your logic within the loop. Although i'm not sure why you'd want to do this.

example:

for (var i = 0; i < json.length; i++) {
   // do something here..
   return;

}

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.