What is preventing me from retrieving the value of this particular key in the customers array?

I am puzzled as to why it's returning undefined instead of true.

function coffeeLoverExtended(customer){
  for (var key in customer) {
    return customer[key]['enjoysCoffee'];
  }
}

var customer001 = {
  name: "John Riley",
  ticketNumber: "A01",
  enjoysCoffee: true
};

console.log(coffeeLoverExtended(customer001)); //true

Answer №1

When you loop over the object customer, you are retrieving the keys one by one. The variable key holds the property within the customer object. So, accessing customer[key]['enjoysCoffee'] essentially means extracting the 'enjoysCoffee' property from the specific key in the customer object.

If there is no property named enjoysCoffee in the customer[enjoysCoffee] object, it will return undefined.

If your intention is to fetch the value of the enjoysCoffee property from the customer object, then the correct syntax should be customer["enjoysCoffee"];

function coffeeLoverExtended(customer) {
  return customer["enjoysCoffee"];
}

var customer001 = {
  name: "John Riley",
  ticketNumber: "A01",
  enjoysCoffee: true,
};

console.log(coffeeLoverExtended(customer001)); //true

To access a property of an object, you have to use either dot notation (.) or bracket notation ([]). Both customer["enjoysCoffee"] and customer.enjoysCoffee would yield the same result.

Here's an example with nested objects:

function coffeeLoverExtended(customer) {
  // return customer.enjoysCoffeeObj["enjoysCoffee"];
  // or
  // return customer["enjoysCoffeeObj"].enjoysCoffee;
  // or
  // return customer["enjoysCoffeeObj"]["enjoysCoffee"];
  // or
  return customer.enjoysCoffeeObj.enjoysCoffee;
}

var customer001 = {
  name: "John Riley",
  ticketNumber: "A01",
  enjoysCoffeeObj: {
    enjoysCoffee: true,
  },
};

console.log(coffeeLoverExtended(customer001)); //true

All the above return statements will output true.

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

Incrementing a variable based on a condition in JavaScript

Currently, I am working on a project where I have a variable called "total" that needs to be assigned a number (or price) and then incremented when certain options are selected or checked. Below is the code that I have developed up to this point. This sni ...

Retrieve the array from the response instead of the object

I need to retrieve specific items from my database and then display them in a table. Below is the SQL query I am using: public async getAliasesListByDomain(req: Request, res: Response): Promise<void> { const { domain } = req.params; const a ...

Tips for Keeping Vuetify Dialog Title at the Top and Ensuring Buttons are Always Visible

My goal was to make the Vuetify dialog title and content headers stay fixed at the top while scrolling. I attempted using "style:position:fixed". However, when I scroll, the headings go out of view. Below is the current code: <v-layout row wrap ...

WebPack bundling causing issues with Knockout Validation

I am developing a web application using Knockout along with the Knockout-Validation plugin, and I want to utilize WebPack for bundling. However, I encountered an issue where Knockout-Validation seems to break when incorporated with WebPack. To illustrate ...

Tips for extracting information from an HTML table into a function using Google Apps Script

I am experiencing difficulties in coding this. I have attempted to use google.script.run but it's not working as expected. When I click the button "Approved," the data should be sent to a function, but I'm unsure of what steps to take next. I fee ...

Warning displayed on form input still allows submission

How can I prevent users from inserting certain words in a form on my website? Even though my code detects these words and displays a popup message, the form still submits the data once the user acknowledges the message. The strange behavior has me puzzled. ...

Choose three different images and one corresponding word from a JavaScript array to be displayed individually on the screen in separate div containers

I am in the process of developing a web game that will showcase 3 images on the screen, and the player must select the image that corresponds to the displayed word. I have successfully created a JavaScript array containing the images and words retrieved fr ...

The AJAX post request is returning an undefined value

I'm working with JavaScript, AJAX, and Node.js but I'm having trouble receiving a value on the server side when making a POST request. Despite my efforts to test it out, the console keeps returning 'value undefined'. Here's a snip ...

Unresolved Axios jsonp request causing code blockage

Recently, I created a function to retrieve Google suggestions: const fetchGoogleSuggestions = async (searchQuery: string) => { const results = await axios({ url: `https://suggestqueries.google.com/complete/search?client=chrome&q=${searchQuery ...

Creating dynamic routes with Nuxt3

Within my nuxt.config.ts file, I have the ability to generate multiple routes using the following code: export default defineNuxtConfig({ generate: { routes: ['/products/1', '/products/2'] }, }) After running nuxt generate, thi ...

How can I create an accordion panel that can be toggled using

I've been working on creating an accordion panel using CSS with a touch of JavaScript. Everything seems to be functioning correctly except for the toggling of the panels. Essentially, when one panel is clicked, I want all other open panels to close. ...

Find the corresponding value in an array by matching it with a key from an Object, and then replace the

In my coding challenge, I am trying to find a way to match the keys from an Object to elements in an array and replace the matching elements in the array with the corresponding key values. Here is what I currently have: Arr = [ 'Saturday& ...

Should I Change or Focus in jQuery? What event is best to use with a select dropdown in order to trigger a call to a jQuery-AJAX function?

I have a single select dropdown element in my HTML code: <select id="student" name="student" class="form-control"></select> I am looking to implement a jQuery-AJAX function that will populate the option values in the select dropdown above. H ...

Unable to properly execute Fetch Delete Request

When using the Fetch API, I am sending this request: const target = e.currentTarget; fetch(target.href, { method: 'delete', }) .then(res => console.log(22)) .catch(err => console.log(err)); In addition, here is the middleware that manag ...

What is the method to disable response validation for image endpoints in Swagger API?

I'm working with a Swagger YAML function that looks like this: /acitem/image: x-swagger-router-controller: image_send get: description: Returns 'image' to the caller operationId: imageSend parameters: ...

What is the best way to access the dimensions of a parent element in React with Hooks?

I am currently working on a new component and I am facing the challenge of obtaining the width and height of its parent <div>. Since all my components are functional ones using Hooks, the examples I found involving classes do not fit my case. Here i ...

When attempting to access AJAX JSON properties using an index within a promise, the result returned is undefined

I have a quiz app that communicates with my server's API using MongoDB. I am trying to access the response indexes in this way: setTimeout(() => { axios.get('/api/ninjas') .then(function (questions) { var data = questions.d ...

Is there a way to update the parent value when the child is activated?

I need to create a dropdown menu for users to select their email provider - either gmail, hotmail, or outlook. Once they make a selection, I want the button text to update accordingly. The catch is that I can only use bootstrap for this project and cannot ...

Make the card change to gray when clicked using Bootstrap

Is it possible to achieve a common function in an infinite list using HTML, CSS, JS, jQuery (on the user's side) where an item will be grayed out after being clicked? How can we implement this effect? 1.) When the user clicks on the card element htt ...

The margin and width of a div element with the position set to fixed and display set to table-cell are not rendering correctly

Is there a way to keep my .nav-container position: fixed; without creating a gap between it and the .page-content at certain window widths? When I set the position to fixed, a small white line appears between the red background of the .nav-container and th ...