Jason
Jason

Reputation: 1817

Protractor: Returning an array of objects from a table

I have a table with 3 columns 'firstname', 'lastname', 'birthday', like this:

<table id="table">
    <tr>
        <td id="firstname">John</td>
        <td id="lastname">Smith</td>
        <td id="birthday">Jan 1 2014</td>
    <tr>
    <tr>
        <td id="firstname">Bill</td>
        <td id="lastname">Matthews</td>
        <td id="birthday">Jan 2 2014</td>
    <tr>
</table>

I want to create a JSON from this table, like this:

{
    firstname: "John",
    lastname:  "Smith",
    birthday:  "Jan 1 2014"
},
{
    firstname: "Bill",
    lastname:  "Matthews",
    birthday:  "Jan 2 2014"
}

I've trying something like this:

var tableRows = [];
element.all(by.tagName('tr')).each( function(element) {
    tableRows.push(
                     {
                         firstname: element(by.id('firstname')).getText(),
                         lastname:  element(by.id('lastname')).getText(),
                         birthday:  element(by.id('lastname')).getText()
                     }
                  );
});

Upvotes: 1

Views: 1562

Answers (1)

alecxe
alecxe

Reputation: 473823

Use map(), quote from the changelog:

Added a map function to element.all to apply a function to each element and return the result of the transformation.

Resolve promises if there is an object that contains multiple promises. Added index as a second argument to the map function callback.

Key point here is that it would resolve multiple promises:

var items = element.all(by.tagName('tr')).map(function (tr) {
    return {
               firstname: tr.element(by.id('firstname')).getText(),
               lastname: tr.element(by.id('lastname')).getText(),
               birthday: tr.element(by.id('birthday')).getText()
           };
});

Upvotes: 3

Related Questions