So i have an array of objects named: tokens. Each object from this array has this format: {tokenName: string}. I want to test if each element from this array has the exact same format or else throw an error.
I have tried this:
for (let i = 0; i < tokens.length; i++) {
if (
typeof tokens[i].tokenName === "string" &&
tokens[i].hasOwnProperty("tokenName")
) {
// do stuff
} else {
throw new Error("Invalid array format");
}
But it won’t pass the test.
>Solution :
Use every to iterate over the array of objects, and apply the test to each object.
In this example tokens1 all objects have the tokenName key, and all are strings. tokens2 has one value that is an integer. tokens3 has a tokenAge key.
const tokens1=[{tokenName:"name1"},{tokenName:"name2"},{tokenName:"name3"},{tokenName:"name4"}],tokens2=[{tokenName:"name1"},{tokenName:"name2"},{tokenName:9},{tokenName:"name4"}],tokens3=[{tokenName:"name1"},{tokenName:"name2"},{tokenAge:"name3"},{tokenName:"name4"}];
// Accept an array of objects
function checkTokenName(tokens) {
// Check the every token object in the
// array passes the condition - true if it
// does, false if it doesn't
return tokens.every(token => {
return (
token.hasOwnProperty('tokenName')
&& typeof token.tokenName === 'string'
);
});
}
console.log(checkTokenName(tokens1));
console.log(checkTokenName(tokens2));
console.log(checkTokenName(tokens3));