Reputation: 3968
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
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
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