Issues
- The
usernames array is an array of objects with the value string you want to search in nested in a link property.
- Array.prototype.map returns an array the same length as the starting array and isn't for issuing side-effect.
Solution
Check for the substring from the link property, and use array.prototype.find or array.prototype.filter to search for matches. find returns the first match or undefined if not found, filter returns all matches in an array.
usernames.find((user) => user.link.includes("gl"));
usernames.filter((user) => user.link.includes("gl"));
Code:
React.useEffect(() => {
let result;
if (usernames != null) {
result = usernames.find((user) => user.link.includes("gl"));
}
console.log(result);
}, []);
const usernames = [
{ link: "apple" },
{ link: "google" },
{ link: "shopify" }
];
let result;
if (usernames != null) {
result = usernames.find((user) => user.link.includes("gl"));
}
console.log(result?.link);
Note: array.prototype.find returns undefined if the value is not found, so you'll likely want to check for nullish values before doing anything with the result, like access the link property, i.e. trying result.link to display "google".
Note 2: If you use filter then the result will be an array. You can either iterate the array, or pop the last value (or unshift the 0th element) to get a single result object. You'll still need to do the null check, something like result?.[0]?.username.