Navigating through arrays to access nested objects

Currently, I am attempting to retrieve a specific field within a nested array using the following code:

var array1 = [];

const data =  { [userId]: [{
             id: id,
             name: fullName,
             email: userEmail },
            ],
          };

array1.push(data);

After printing this using

console.log("index 0: ", array1[0]);
, the output is:

index 0:  {
  buMqSZpEaKZABffDGNs5jzVK36Y2: [
    {
      id: '65',
      name: 'nameTest',
      email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="aec3d7cbd6c3cfc7c2eec9c3cfc7c280cdc1c3">[email protected]</a>'
    }
  ]
}

However, I am trying to figure out how to access the information within the userId, such as userId.name and locate a specific userId like "aePoUZpkUnlAOMNBGNs5ynMD36L1" in array1 to display its details similar to activeSockets[0]. or using indexOf(). Whenever I attempt to access the fields inside, it often results in a

Cannot read property '' of undefined
error. Any guidance on this issue would be highly appreciated.

Answer №1

To discover the object associated with the user ID within an array, you can utilize the following code:

var array1 = [];

var data =  { ['ABC123']: [{
     id: 1,
     name: 'john',
     email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="62080d0a0c4c060d07220c0d0f030b0e4c010d0f">[email protected]</a>'
      },
    ],
  };

array1.push(data);

let userId = 'ABC123';

let userObj = array1.find((x)=> x[userId] !== undefined);

if(userObj) {
    let userData = userObj[userId][0];
    console.log(`name: ${userData.name}`);
    console.log(userData);
}
else {
    console.log(`user ${userId} not found.`);
}

In most cases, utilizing a value as a property name is not common practice, but rather using it as a property value in objects.

This approach simplifies the use of find or filter.

For instance:

var array1 = [];

array1.push({
         userid : 'ABC123',
         id: 1,
         name: 'john',
         email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ddb7b2b5b3f3b9b2b89db3b2b0bcb4b1f3beb2b0">[email protected]</a>'
      });

let userId = 'ABC123';
let userData = array1.find((x)=> x.userid === userId);

if(userData) {
    console.log(`name: ${userData.name}`);
    console.log(userData);
}
else {
    console.log(`user ${userId} not found.`);
}

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

There is a syntax error in the for-loop within the AngularJS $http.get causing an unexpected identifier

I'm encountering a 'syntax error: unexpected identifier' and my browser seems to be getting stuck in a loop after executing this code. I figured incorporating setInterval for delaying API requests was a sound strategy according to the API re ...

swapping out an external CSS file in React for a new CSS file

My React app is quite large and includes four main CSS files (darkLTR, lightLTR, darkRTL, lightRTL), which may not be the most efficient setup. The templates were provided by my boss, and I was instructed to use them instead of Material UI, which I initial ...

What is the best way to add a CSS rule to JavaScript?

animation: scaleUp 0.3s linear 0.4s forwards; animation: scaleDown 0.3s linear forwards; Greetings! I'm currently working on adding animations to my content filtering functionality. Specifically, I want to incorporate the aforementioned CSS rules in ...

Is there a way to adjust the label size for a material ui TextField component?

My TextField element is defined like this: <TextField id="standard-with-placeholder" label="First Name" className={classes.textField} margin="normal" /> It currently appears as shown in the image below: However, I would like it to look mor ...

Navigating to a new URL using window.location.href will seamlessly embed the new page within

I am new to JavaScript and I am facing an issue with my AJAX function. The function is supposed to navigate to a new URL, but instead of loading the new page separately as if the user had typed the URL, it gets inserted inside the same div where the button ...

Highcharts-ng allows us to create charts without using the traditional syntax such as $('#container').high

After setting up the chart's configuration in my controller, I am facing an issue. The HighCharts-ng (an angularJS directive for HighCharts) has a method that I want to implement: $scope.ohlcChartConfig = { options: {....... I ne ...

Grab the URL from React Router

I need assistance with writing a function that updates the current location to match the route of a clicked button. Currently, the code is returning the URL of the page where the button was clicked, not the path related to the button itself. Are there an ...

Exploring VueJs 3's Composition API with Jest: Testing the emission of input component events

I need help testing the event emitting functionality of a VueJs 3 input component. Below is my current code: TextInput <template> <input v-model="input" /> </template> <script> import { watch } from '@vue/composition-api&ap ...

Unlock the Power of TWBS Ratchet: Manually Closing Modal Windows

Currently, I am in the process of developing a mobile web application using Ratchet. The main task at hand involves opening a modal, filling out a form, clicking a button to save the input data, and then closing the modal. Although I have managed to close ...

Do not use unnecessary variables for storing references in ES6

Despite using react es6, I am still unsure how to refrain from needing to use the variable that for this scenario: const that = this; UploadApi.exec(file).then(data => { that.setState({ loading : false}); }); ...

Display the closest locations on the Google Maps interface

I am currently working on a project that involves integrating Google Maps. The project includes storing hospital addresses (in longitude and latitude) in a database. However, I need assistance in displaying the nearest hospital from my current location. I ...

Having trouble with changing the state within an AngularJS (Ionic Framework) controller?

My goal is to switch views within the Search controller after receiving search results from the server through $http. However, my current approach doesn't seem to be working as intended. I also need to pass the response to the new view for displaying ...

Is it more beneficial to categorize REST-based modules/controllers by resource or by specific action/feature?

I'm facing a scenario that goes like this: Endpoint 1: Retrieve all books in the United States owned by John with a GET Request to /country/us/person/john/books Endpoint 2: Get all books owned by John in every country with a GET Request to /person/j ...

Runtime.UnhandledPromiseRejection - Oops! Looks like we're trying to read properties of something that doesn't exist (specifically 'headers')

I'm facing an unexpected error that has left me puzzled. Let me walk you through what I am trying to accomplish: The task at hand involves fetching data from one API and then transmitting it to another. This process is executed as a background-funct ...

Struggling to merge two variables together and receiving this error message: "mergedObject is not defined."

New to Node.js/Express and trying to combine two objects to save them to a collection. Any advice would be greatly appreciated! Thank you in advance for your time. This is what I've put together, but it's not functioning as expected: app.post( ...

What could be causing the Universal Code for Disqus to not function properly?

Struggling to get this code to work on my website. I've tried everything, from clearing caches and cookies to disabling plugins and extensions, but still no luck. Check out the code below: import React, { Component } from 'react' import { ...

The step-by-step guide on passing arguments and fetching results from Angular UI Bootstrap Modal through Components

I am facing a simple scenario where I have defined a modal as a component and opened that modal using `uiModal.open`. However, when I try to pass custom data to the modal using "resolve" in the open method and arguments in the controller constructor, the d ...

Cassandra encountered a TypeError stating that the "value" argument is exceeding the bounds

I keep encountering the error message below. Any thoughts on what might be causing it? TypeError: "value" argument is out of bounds at checkInt (buffer.js:1041:11) at Buffer.writeInt32BE (buffer.js:1244:5) at Encoder.encodeInt (/ ...

Exploring the optimal approach for distinguishing between numbers and strings in a JavaScript/Typescript class

I recently encountered a situation with my Typescript/React solution where I defined a property as a number and set the input type to "number", but when the state value was placed in an input field, it would change to a string unless properly handled. In ...

What is the process for sending an InMemoryUploadedFile to my S3 storage?

My upload form is quite simple and includes an image as a FileField: def post(request): if request.user.is_authenticated(): form_post = PostForm(request.POST or None, request.FILES or None) if form_post.is_valid(): inst ...