I want to loop over the array and make my loop return function or one time string to say the name exist? this is the error TypeError: Cannot read property 'name' of undefined var x = arr[i].name;
var arr = [
{id: 1, name: "php"},
{id: 2, name: "mysql"},
{id: 3, name: "laravel"},
{id: 4, name: "codeigniter"},
{id: 5, name: "wordpress"},
{id: 6, name: "sql"},
{id: 7, name: "jquery"},
{id: 8, name: "javascript"},
];
var string;
function checkemail(arr, string) {
var i;
for (i = 0; i < arr.length; i++) {
let newname = arr[i].name;
if (newname !== string) {
return storename();
} else {
console.log("name found")
}
}
}
}
console.log(checkemail(arr, "javascript"));
You should loop through the entire array before making a decision on the existence of the element in the array
You are calling storename function on the first mismatch of the name and parameter. This will make the function checking the first element and return after calling storename function.
My implementation
function storename() {
return 'storename function';
}
var arr = [
{ id: 1, name: "php" },
{ id: 2, name: "mysql" },
{ id: 3, name: "laravel" },
{ id: 4, name: "codeigniter" },
{ id: 5, name: "wordpress" },
{ id: 6, name: "sql" },
{ id: 7, name: "jquery" },
{ id: 8, name: "javascript" },
];
var string;
function checkemail(arr, string) {
var i;
let isFound = false;
for (i = 0; i < arr.length; i++) {
let newname = arr[i].name;
if (newname === string) {
isFound = true;
i = arr.length; // Item found, you can exit the loop now
return "name found";
}
}
if(!isFound) {
return storename()
}
}
console.log(checkemail(arr, "javascript"));
Array.find implementation:
You can implement the same logic without using a manual loop by using Array.find as below.
var arr = [
{ id: 1, name: "php" },
{ id: 2, name: "mysql" },
{ id: 3, name: "laravel" },
{ id: 4, name: "codeigniter" },
{ id: 5, name: "wordpress" },
{ id: 6, name: "sql" },
{ id: 7, name: "jquery" },
{ id: 8, name: "javascript" },
];
var string;
function storename() {
return 'storename function';
}
function checkemail(arr, string) {
const node = arr.find(item => item.name === string);
return node ? "name found" : storename();
}
console.log(checkemail(arr, "javascript"));