What is the best way to connect methods using variables?

const people = {
  person1: {
    first: "Yassine",
    last: "Boutabia",       
  },
  person2: {
    first: "Md Jahidul Hasan",
    last: "Mozumder",
  },
  person3: {
    first: "Md Feroj",
    last: "Ahmod",
  },
}

retrieveInfo = () => {
  var propName = "first"; //an idea that occurred to me
  var array = [];
  for (var key in people) {
    if (people.hasOwnProperty(key)) {
      array.push(people[key]);
    }
  }
  console.log(array[0][propName]);
}

the variable array represents the people objects as an array here. When I write console.log(array[0].first);, it outputs the first of person1 which is Yassine. So far so good. Now, I am trying to retrieve this value using a variable. I want to store either the first or last in a variable and append it to the end of array[0] so I can get that specific value. How can this be achieved?

Answer №1

Always remember to enclose elements in square brackets []

Display the value at index 0 of the array using console.log(arr[0][val]);

Answer №2

Utilize the power of the map function to customize the array as needed before showcasing it.

people
  .map(person => `${person.first} ${person.last}`)
  .forEach(fullName => console.log(fullName))

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

Implementing a queue with an on-click event

As a self-proclaimed Java nerd diving into the world of jQuery, I'm facing some challenges. My goal is to create 3 interactive boxes that behave in a specific way: when clicked, one box should come forward while the other two dim and stay in the back ...

Deciphering the nuances of middleware and route handling in Express.js

I'm currently exploring the inner workings of middleware and route handlers in Express. In Web Development with Node and Express, the author presents an intriguing scenario involving a route and middleware, but leaves out the specific details. Could ...

Is there an alternative to Captcha?

Seeking suggestions for a lightweight and simple anti-bot/spam protection method for a basic registration form on my website. I find Captcha annoying and time-consuming. Any alternative suggestions that are easy to integrate and effective against spam? ...

Display some results at the conclusion of eslint processing

As I develop a custom eslint plugin, I am intricately analyzing every MemberExpression to gather important data. Once all the expressions have been processed, I want to present a summary based on this data. Is there a specific event in eslint, such as "a ...

Using RxJS with Angular 2 to Split Observables in an Array

Looking for an API to return back an array and then split it into components for use with the "take" function of Observables. Currently working with Angular 2 / RxJS. This is my functioning code: public getFiltered(groupName:string, start?:number, num?: ...

Is there a way to automatically refresh a page as soon as it is accessed?

My goal is to create a page refresh effect (similar to pressing Command+R on Mac OS) when navigating to a certain page. For instance: Currently, when I navigate from "abc.com/login" to "abc.com/dashboard" after successfully logging in, the transition occ ...

Issue: Unrecognized element type in next.js while starting development server

Every time I run npm run dev, I encounter the following error: Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from th ...

A guide to entering information into an input field with JavaScript for logging in successfully

https://i.stack.imgur.com/TF51Z.gif https://i.stack.imgur.com/HHsax.png https://i.stack.imgur.com/HUztt.png When attempting to input text using document.getelement('').value="" , it doesn't behave as expected. The text disappear ...

What causes the disparity between the outcomes of double matrices compared to integer matrices within Java programming?

There are two codes available that perform the same function, with one utilizing an integer array and the other using a double array. The first code runs perfectly fine, but there are many errors in the second one. Both codes are supposed to iterate throug ...

Issue with FullCalendar: Changing ajax parameters dynamically after the initial load is not functioning as expected

I am currently exploring the functionalities of and I am interested in dynamically filtering the events displayed based on checkboxes present on the page. To achieve this, I am utilizing an ajax source with filters passed as parameters to fetch the necess ...

Stopping XSS Attacks in Express.js by Disabling Script Execution from POST Requests

Just starting to learn ExpressJs. I have a query regarding executing posted javascript app.get('/nothing/:code', function(req, res) { var code = req.params.code; res.send(code) }); When I POST a javascript tag, it ends up getting execut ...

Issue with authentication when accessing Google Video API

I'm attempting to utilize the Google API provided: I have downloaded the Sample Project and followed these steps: 1) Navigate to the Project Folder named API Video 2) Run npm install 3) Set GCLOUD_PROJECT = neorisvideo 4) Download Json from the C ...

Enhance array processing speed in Python

Dealing with numerous arrays containing 512x256 pixel-like data, most entries are 0, and the focus is on saving the non-zero values only. Essentially: import numpy as np import time xlist=[] ylist=[] zlist=[] millis = time.time()*1000 ar = np.zeros((512 ...

Steps for deactivating an eventhandler while another is being triggered:

There are two event listeners attached to a single input field. One triggers on change, while the other activates when selecting an autocomplete suggestion from Google. The issue arises when interacting with an autocompletion option as both handlers execut ...

Angular2 - ERROR: Route configuration must have only one "component" specified

Currently, I am facing an issue with my routing in Angular 2 while trying to navigate between two simple pages. The exception that I'm encountering is as follows: EXCEPTION: Error during instantiation of Router! (RouterLink -> Router). ORIGINAL E ...

Transforming a multi-dimensional array into a single level using Javascript

I'm currently faced with the challenge of converting a complex object array document into a single-level array. Here's an example: const data = [ { "id": 1, "name": "Beauty", "childre ...

Async Await is returning an undefined array in the function

My getJSON function is not returning the array I need. I have been attempting to use await/async, but it seems like there might be an error in my approach. The methods .map and .filter are supposed to be synchronous, but even adding await does not seem to ...

The functionality of the Toastr "options" seems to be malfunctioning

I am having some trouble with my Toastr notification messages. While the message does display, I seem to be unable to make use of any options that I set. Despite specifying some options, they do not seem to work as intended. $('#editButton').c ...

Loop through a SimpleXMLElement array and save each element to its own text file

I've encountered a challenge that has me stumped. I have an array of SimpleXMLElement objects containing PDF data bytes. My goal is to loop through the array, writing each chunk of PDF data bytes to separate text files so that I can later convert them ...

Refresh Quantity of item without needing to reload the page

I am currently working on a project and faced with a challenging situation. When a user adds a product to the cart, I need to verify both the quantity added and the specific product. To achieve this, I am utilizing a JQuery function. While the user is sti ...