Gambit2007
Gambit2007

Reputation: 3968

Testing values of array objects

If i have an array like:

[
{ "user": "tom",
  "email": "[email protected]"
},
{ "user": "james",
  "email": "[email protected]"
},
{ "user": "ryan",
  "email": "[email protected]"
}
]

But it's not always being returned in that order - how can i check if ryan, for example, exists somewhere in one of these objects?

Upvotes: 3

Views: 1363

Answers (3)

deerawan
deerawan

Reputation: 8443

My method to solve that is to extract the targeted fields into arrays then check the value.

const chai = require('chai');
const expect = chai.expect;

describe('unit test', function() {
  it('runs test', function() {
    const users = [
      { "user": "tom",
        "email": "[email protected]"
      },
      { "user": "james",
        "email": "[email protected]"
      },
      { "user": "ryan",
        "email": "[email protected]"
      }
    ];
    const names = extractField(users, 'user'); // ['tom', 'james', 'ryan']   

    expect(names).to.include('ryan');
  });

  function extractField(users, fieldName) {
    return users.map(user => user[fieldName]);
  }
});

I'm using chai for assertion. In case you want to check in other fields, we just use the extract methods.

const emails = extractField(users, 'email');
expect(emails).to.include('ryan');

Hope it helps

Upvotes: 0

front_end_dev
front_end_dev

Reputation: 2056

Function return true if array contains ryan.

var input = [
{ "user": "tom",
  "email": "[email protected]"
},
{ "user": "james",
  "email": "[email protected]"
},
{ "user": "ryan",
  "email": "[email protected]"
}
]
var output = input.some(function(eachRow){
    return eachRow.user === 'ryan';
});

console.log(output);

Upvotes: 1

Will
Will

Reputation: 7027

If you are already using lodash (or want to) then I would use its find:

_.find(array, { user: "ryan" })

Or with a few more characters you can do it without lodash:

array.find(elem => elem.user === "ryan")

Both return undefined if a matching element is not found.

Upvotes: 2

Related Questions