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

Enhancing bar chart presentation with text in d3

Looking to enhance my bar chart by adding text tooltips that appear when hovering over each bar. While I am a beginner with d3, I've been struggling to implement this feature effectively. Despite trying various methods gleaned from online resources, t ...

Optimal method for storing large arrays of numbers in localStorage using JavaScript

*"Efficient" in this context refers to smaller size (to reduce IO waiting time) and fast retrieval/deserialization times. Storing times are less important in this scenario. I need to store multiple arrays of integers in the browser's localStorage, ea ...

Ways to enhance radio imagery selection?

I'm just starting out with JS and could really use some guidance on how to improve my code. I think it might need a single function for all options, but I'm not sure. It's working fine right now, but I have a feeling it could be better ;) H ...

AngularJS Time Range Selector: A Slider Solution

I have successfully implemented a time range slider using Jquery and JqueryUI. $("#slider-range").slider({ range: true, min: 0, max: 1440, step: 15, values: [600, 720], slide: function (e, ui) { var hours1 = Math.floor(ui.values[0] / 60); var minu ...

"Capturing the essence of your online presence: The

I recently completed a website for my Students Organization, which includes a special page dedicated to recognizing the individuals who helped organize our activities. Each member is represented with a photo on this page, sourced from their Facebook profil ...

Select a Date: Input for Date Selection

Is it possible to restrict the selection of certain days using HTML date input validation? Some booking websites have a feature where an interactive calendar only allows users to select specific dates for events, while others are greyed out and cannot be c ...

The resolveMX function in Google Cloud Functions is encountering issues when trying to process a list of domains

Here is the task at hand. I have a large list of domains, over 100,000 in total, and I need to iterate through them using a foreach loop to resolve MX records for each domain. Once resolved, I then save the MX records into another database. Below is the c ...

Iterating over an object and inserting values into a JavaScript object using the ascending count as the identifier

Illustration: { Are you a coffee drinker?: yes, Do you like to exercise regularly?: no, How often do you eat out at restaurants?: 3 times a week, What is your favorite type of cuisine?: Italian } Results: {yes: 1, no: 1, 3 time ...

Javascript generates a mapping of values contained within an array

In my current project, I am developing a feature that allows users to create customizable email templates with placeholder tags for content. These tags are structured like [FirstName] [LastName]. My goal is to brainstorm the most effective method for crea ...

Error with Chakra UI and React Hook Form mismatched data types

Struggling with creating a form using ChakraUI and React-Hook-Form in TypeScript. The errors seem to be related to TypeScript issues. I simply copied and pasted this code from the template provided on Chakra's website. Here is the snippet: import { ...

Altering the DOM directly within the componentDidMount() lifecycle method without needing to use

In ReactJS, I am facing an issue while trying to manipulate the DOM in the componentDidMount() method. The problem lies in the fact that the DOM is not fully rendered at this point, requiring me to use a setTimeout function, which I find undesirable. Upon ...

Angularjs 2 Error: Unable to access the 'infos' property of an undefined object using the Http Client

I've been working on an AngularJS app for about a week now, developing a backoffice application for my service. My main challenge lies in using data retrieved from a remote server. I have 4 HTTP GET requests in my app - 2 of them fetching lists of us ...

Struggling to maintain context with axios in React despite diligent use of arrow functions

In my component, I have a function for posting data. Although it works well, the context of my component is lost in the success message. This is puzzling because I am using arrow functions. Why does the "this" context get lost in this situation? The issu ...

Using onchange within an onchange event will not function as intended

When I am in the process of creating 2 dropdown menus filled from a database, the issue arises when the second dropdown is generated after selecting a value from the first one. Upon choosing an option from the second dropdown, my ajax function is triggered ...

Updating token using an Ajax request in a PHP webpage

Currently, I am encountering an issue with my token system for requesting PHP pages via Ajax. The problem arises when attempting to make multiple Ajax requests from the same page as I am unable to refresh the token on the initial page. To elaborate furthe ...

Is it possible to import SVG files and inline them in Angular?

Behold, an SVG Circle: <svg viewBox="0 0 104 104"> <circle cx="52" cy="52" r="50" stroke="#003EFF" stroke-width="4" fill="#00FF98" /> </svg> The Angular Project imports it in this manner: import circle from './circle.svg'; ...

Using two loops/arrays in JavaScript to generate a rating score

I want to create a simple rating component with the following appearance: ◼◼◼◻◻ (score: 3 out of 5) Here is my JSX code snippet: var score = 3; var range = 5; { [...Array(range)].map((e, i) => ( <div className="rating-item" ...

Tips for verifying the "truthiness" of an object, removing any falsy values, and making changes to the object

I am faced with the task of examining each property of an object to determine if it is truthy, and then removing any that are not. var user = { name: 'my name', email: null, pwHash: 'U+Ldlngx2BYQk', birthday: undefined, username: &ap ...

Having trouble with some JS and Jquery codes not functioning properly in IE until the page is refreshed a few times. Any suggestions on how to fix this issue?

My code seems to be experiencing issues in Internet Explorer where some of the JS and jQuery codes are not functioning correctly initially, but start working after refreshing the page a few times. Any thoughts on why this could be happening? Here is the ...

The React useEffect hook runs whenever there is a change in the state

Within my React component, I have the following code snippet (excluding the return statement for relevance): const App = () => { let webSocket = new WebSocket(WS_URL); const [image, setImage] = useState({}); const [bannerName, setBannerName] = use ...