What is the reason behind value1.a[x] and value2.b[x] being returned as undefined even though a[x] and b[x] are properties of value1 and value2 objects in JavaScript?

let obj1 = {a:5, b:6}, obj2 = {a:8, b:7};
let keysObj1 = Object.keys(obj1), keysObj2 = Object.keys(obj2);
  for (let i = 0; i < keysObj1.length; i ++) { 
    if (keysObj1[i] === keysObj2[i] && obj1[keysObj1[i]] === obj2[keysObj2[i]]) {
      console.log(keysObj1[i], keysObj2[i], obj1[keysObj1[i]], obj2[keysObj2[i]]);
    }
  }
// -> a, a, undefined, undefined

P.S. I am aware of alternative methods to compare objects; I just wanted to investigate why this particular approach didn't yield the expected results.

Answer №1

The notation being utilized is as follows:

value1.a[x]

It attempts to access the a property of value1 as if it were an array (or another indexable object like a string), using x as the indexer. However, since value1.a is a number, this will result in undefined.

To reference the property of value1 with the name a[x], you should use the following syntax instead:

value1[a[x]]

For instance:

value1 = {
  a: 5,
  b: 6
}, value2 = {
  a: 5,
  b: 7
};
let a = Object.keys(value1),
  b = Object.keys(value2);
for (let x = 0; x < a.length; x++) {
  if (a[x] === b[x] && value1[a[x]] === value2[b[x]]) {
    console.log(a[x], b[x], value1[a[x]], value2[b[x]]);
  }
}

It is important to note that if value1.a and value2.b are strings, the code provided will function (albeit producing unexpected outcomes). For example:

value1 = {
  a: 'abc',
  b: 6
}, value2 = {
  a: 5,
  b:  'abc'
};
let a = Object.keys(value1),
  b = Object.keys(value2);
for (let x = 0; x < a.length; x++) {
  if (a[x] === b[x] && value1.a[x] === value2.b[x]) {
    console.log(a[x], b[x], value1.a[x], value2.b[x]);
  }
}

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

Tips for getting information from firestore by implementing a where clause specific to a field within an object?

In my React Native project, I am utilizing Firebase Firestore as the backend database. I have successfully retrieved data from the database using the following code: unsubscribe = firebase.firestore().collection('messages').where('user&apos ...

Utilizing the progress or meter tag in combination with a reactive value

Within my Vue class-based component, I am aiming to utilize a reactive value to showcase real-time progress changes using either a <progress> or <meter> tag. To achieve this, I have defined a variable that contains an initial base value: perce ...

Utilize a variable function in AngularJS

Within my app.js file, I have declared functions in the following manner: var func1 = function(v1,v2,v3) { . . } var func2 = function(v1,v2,v3) { . . } Moving on to my controller.js file: var action = ""; if(..) { action = 'func1';} ...

How to use Javascript to pause an HTML5 video when closed

I am new to coding and currently working on a project in Adobe Edge Animate. I have managed to create a return button that allows users to close out of a video and go back to the main menu. However, I am facing an issue where the video audio continues to p ...

Prevent jQuery toggle from animating content when toggling

When I use a simple jQuery .toggle function to show/hide my content on click, it slides in from left to right before reaching its final position. Is there a way to prevent this sliding effect? Is there a different jQuery method or property that I should be ...

An error occurred as the requested resource does not have the necessary 'Access-Control-Allow-Origin' header. The response code received was 403

I am working with Angular products services that make calls to the "http://jsonplaceholder.typicode.com/posts" URL using the HttpClient method. However, I am encountering the error message "No 'Access-Control-Allow-Origin' header is present on t ...

Analyzing file to determine optimal size for HashTable compared to frequent resizing of Array and constant rehashing, along with other related inquiries

Currently, I am working on a project that involves identifying anagrams within a given file. Each line in the file contains a different word. Here is what I have already accomplished: 1.) I have sorted the words (using Mergesort - as I believe this metho ...

What does the concept of hydration entail when working with React?

Recently, I've been delving into the world of React and stumbled upon the concept of hydration. Unfortunately, I'm a bit confused about how it operates. Can anyone provide some insights? Thank you in advance. While working on my React app, I enc ...

Is your $http request causing an XML parsing issue?

I'm attempting to utilize the $HTTP method from angularJS to access my restful web service. On entering my web service URL in the browser, I receive a result of APPLICATION/JSON type. {"id":20418,"content":"Hello, World!"} The URL for my web servic ...

When trying to manually trigger the firing of the autocomplete function to get a place using Google API

My goal is to retrieve the data from autocomplete.getPlace() when triggering this event manually. Essentially, I have a function that captures the user's location in Lat/Lng format, and afterward, I aim to access other useful data using getPlace() su ...

Can we utilize conditions to both select and deselect items using JavaScript and PHP together?

I have a selection list with checkboxes that is dynamically generated based on certain conditions in the code snippet below. if ($data_inteiro_01 <= $data_inteiro_02) { if ($parcela[$i] === 0) { $display = 'disabled'; } } els ...

Sending an array to a component in Angular without the need for a controller

How can I pass an array to a component in Angular 1 without being inside a controller (using a component-only approach)? Currently, my starting point is: <user-list users="users"></user-list> The 'users' variable is a JavaScript arr ...

Is there a way to convert a PHP $_POST array into a string that can be used as a name attribute?

Query: I have a collection of post values structured like this: $_POST['children'] = array( [0]=>array( 'fname' => 'name', 'mname' => 'mname', 'lname' => 'lname, 'dob' ...

Please explain the purpose and scope of a JavaScript document

let page = "temp"; function showPage() { alert(page); // temp or HTML Page } When I tried it, the result was "HTML Page", which makes sense. Is 'page' an object, reserved word, or a constant? If 'page' is an object, shouldn' ...

Is there a more efficient way to consolidate multiple functions like this into one cohesive function instead of having to define each one separately?

After attempting to implement a loop without success, I also considered using regex but that did not work either. The code in question is part of a larger project that involves dynamically adding and deleting fields using jQuery. The classes and ids used f ...

jQuery does not support animations for sliding up or down

I'm struggling to conceal a navigation element once the top of the #preFooter section is scrolled to. In order to make the nav element mobile-friendly, I have designed both the .tab-wrap and .tab-wrap-mobile. To enable these elements to slide away w ...

By incorporating JavaScript, clicking on an image will trigger a shift in the position of a different element

Just starting out with JavaScript and experimenting with creating an event where clicking on an image triggers the movement of another hidden image. The hidden image is positioned off-screen to the left, while there is a table of images in the center of th ...

How can we incorporate an algorithmic solution into an Angular brand carousel?

I am seeking to create a brand slider in Angular without relying on any external libraries or packages. The functionality I desire is as follows: 1 2 3(active) 4 5 2 3 4(active) 5 6 3 4 5(active) 6 7 4 5 6(active) 7 (empty) 5 6 7(active) (empty) (empt ...

Is there a way to extract a particular value from a JSON URL and transfer it to a JavaScript variable?

I am looking to extract current exchange rates from a JSON URL for implementation in a webpage. Specifically, I want to retrieve a particular exchange rate (such as the US Dollar) and store it in a variable for use within a JavaScript function. Below is a ...