JavaScript array unexpectedly encounters undefined property in the middle

Currently, I am attempting to compare each item in two arrays to find matches. At the moment, I am only comparing one attribute, but I aim to expand that to two once I resolve this issue.

I'm puzzled by the fact that it successfully processes the first three items in the array but encounters an error on the fourth one. Below is the Chrome console output:

Washington  
Smith  
yes  
Jones  
Uncaught TypeError: Cannot read property 'name' of undefined  

Below is my JavaScript code snippet:

var self = this;
self.people = [
    { id: '1', name: 'Washington' },
    { id: '2', name: 'Smith' },
    { id: '1', name: 'Jones' },
    { id: '1', name: 'Smith' },
    { id: '3', name: 'Washington' }
];

self.params = [
    {id: '1', name: 'Jones'},
    {id: '2', name: 'Smith'}];

for (var val in self.params) {
    for (var value in self.people) {
        console.log(self.people[value].name);
        if (self.people[value].name == self.params[value].name) {
            console.log('yes');
        }
    }
}

If I eliminate the if statement, the code functions without errors and outputs the "names" in the people array twice as expected. Any ideas? Thank you in advance!

Answer №1

It appears that you have re-used the variable name "value" twice in your code.

Just a heads up, in JavaScript variables are not scoped at the block level like you might expect, but rather they are either global or function scoped.

Not entirely clear on what you're trying to accomplish here, but perhaps these following lines of code can provide some guidance:

var val,
   value;
for (val in object.values) {
    for (value in object.items) {
        console.log(object.items[value].name);
        if (object.items[value].name === object.values[val].name) {
            console.log('match');
        }
    }
}

Answer №2

for (let key in user.input) {
    for (let entry in user.data) {
        console.log(user.data[entry].title);
        if (user.data[entry].title == user.input[key].title) {
            console.log('match found');
        }
    }
}

Consider using unique variables for each loop to avoid confusion and potential errors.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Attempting to condense an array of objects into a consolidated and combined array of objects

My array of objects is structured like this: dataArray = [ {Revenue: 5, Date: "2018-06-05T00:00:00", DateString: "6/5/2018"}, {Revenue: 10, Date: "2018-06-05T00:00:00", DateString: "6/5/2018"}, {Revenue: 5, Date: "2018-06-05T00:00:00", DateSt ...

The art of loading STL files in Three.js

Attempting to load an stl file by tweaking the function load of the loader URL in this particular example: However, despite the loading process and subsequent rotation of the scene after a while, visualization seems impossible. Upon checking the mesh deta ...

"PHP error: Accessing an undefined offset index 2

I'm currently working on a code snippet where I need to iterate through an array and replace specific characters within the 'color_codes' values. While the code is functioning correctly, I'm encountering an error message stating undefin ...

My three.js program isn't displaying anything on the screen, even though I'm confident that my

Currently, I am delving into the world of three.js with the aim of creating a 3D showroom showcasing a few planets. I have managed to create the moon, but alas, all that greets me upon running my code is a dismal black screen. Here's the code I have p ...

What is the best way to automatically focus on a select input field after making an

I'm currently facing an issue with the implementation of Material UI's Autocomplete component. The problem arises when I have a debounced API call triggered by user input, which temporarily disables the text input field until the call is complete ...

Access granted to endpoint

I decided to implement a custom decorator for authentication across all controllers in my nest application. Here's the code snippet: export function AuthRequired(exposeOptions?: ExposeOptions): (arg0: Controller, arg1: string, arg3: TypedPropertyDescr ...

What will occur if I pass a variable through numerous requires()?

Currently, I have the players variable being passed down 3 levels within my NodeJS folder structure. It all starts in server.js file: var players = {}; require('./routines')(players); This is what's inside the routines directory, specific ...

Using SignalR 2.0 to connect to a hub without relying on a proxy

By using the HTML/JS code below, I have been able to successfully connect to my SignalR 2.0 hub when both the HTML/JS and hub are on the same server. <!DOCTYPE html> <html> <head> <title>Test SignalR 2.0</title> <style typ ...

What steps can I take to identify and rectify mistakes in this instance

When working with a router and two asynchronous fetches from the database, how can errors be effectively caught in this scenario? router.get('/restaurant/:id', async (req, res, next) => { var current_restaurant = await Restaurant.findOne( ...

Guide on implementing register helpers with node.js and express handlebars

When loading a record, I have a select option on my form and want to pre-select the saved option. Here is the code: The Student.hbs file displays the form, with the act obj coming from the student.js route student.hbs <form> <div class="for ...

Retrieving a name from a multidimensional array with multiple levels of depth

I have a complex multidimensional array that can be extended to multiple levels. My goal is to retrieve only the names in a hierarchical structure from child to parent. For instance, the desired output would be: name => "Sport/Algemeen/techn.sp.ondgd ...

Swap out the image for a div element if the image is not found

Is there a way to accurately display an image if it's available, and use a div as a replacement if the image is not present? // How can I determine `imageExists` without encountering cross-origin issues? (imageExists) ? (<img class="avatar-img" sr ...

Utilizing AJAX and jQuery to Swap Out a div

I have been attempting to update the content of a blank div after making an AJAX call with the data message. I connected the function to my CHtml::submitButton, expecting it to execute when clicked, but unfortunately nothing is happening. Any advice on how ...

Implementing jQuery validation on tab key press

Is it possible to implement field validation in JSP while tabbing through the fields using jQuery? Here is a snippet of my JSP page: <form:form method="POST" commandName="test" name="testname" onclick="submitForm();" > <div> <form:inpu ...

Acquiring data within a jade template in order to generate static HTML pages

I am struggling to pass data to a jade template in order to generate static content. While I am not well-versed in node.js and express, I use jade as a template engine for creating static html. Many of the requests in the jade issue list pertain to includ ...

JavaScript types in TypeScript

In my project, I work with TypeScript and import Three.js library. But here's the twist - I don't have access to NPM or node-modules. So, what I did was add custom paths in my ts-config.json under compilerOptions. "paths": { "th ...

Unusual Occurrences Involving window.location.hash Featuring Periods and Dots

Something completely unexpected happened. Here is an example of my URL structure: www.mywebsite.com/main/folder1/folder2/123/some-content-1/page.1.2.html When I try to update the URL with a hash for dynamic user interaction, everything works smoothly ex ...

Can a JavaScript framework be created to ensure all browsers adhere to standards?

As someone who isn't an expert in JavaScript, I wonder if it's feasible to create a comprehensive embeddable JavaScript file that ensures all browsers adhere to standards. Could there be a compilation of known JavaScript hacks that compel each br ...

What is the best way to store and present data dynamically in D3.js?

Currently, I'm engaged in a project involving my Raspberry Pi that focuses on a sensor collecting data continuously. My objective is to save this data in a specific format such as SQL, CSV, JSON, or any other suitable option, and then present it visua ...

What is the best way to display just the first four HTML elements while concealing the others?

Looking for a solution to display only the first 4 child elements of a menu list initially, with the option for users to click 'show more' to reveal the remaining items? Want to achieve this using CSS, JavaScript, and jQuery without altering the ...