The console is failing to display the value associated with the key

In this snippet of JSON code, the key "pants" is nested under the "children" key for MALE when gender is selected as male. However, if the selected gender is female, then "pants" becomes a children key of FEMALE.

var data = {
  "gender": "male",
  "myFilter": {
    "MALE": {
      "pants": ["33", "34"]
    },
    "FEMALE": {}
  }
}

console.log(myFilter.data[gender.value].pants[0]);

I am looking to modify this code to make it more efficient. Instead of using the selected gender directly as a key, I want to utilize it as a variable key. So far, my attempts have been unsuccessful.

data contains the entire JSON payload.

Answer №1

let userData = {
  "gender": "female",
  "myFilters": {
    "MALE": {
      "pants": ["30", "32"]
    },
    "FEMALE": {
      "pants": ["27", "28"]
    }
  }
}
let selectedGender = userData.gender.toUpperCase();
let pantsSize = userData.myFilters[selectedGender].pants;
for(let j=0; j<pantsSize.length; j++){
 console.log(pantsSize[j])
}

Answer №2

let selectedPants = data.gender.toLowerCase() === 'male' 
  ? data.myFilter.MALE.pants[0]
  : data.myFilter.FEMALE.pants[0];

To handle Dynamic Keys

let selectedPants = data.myFilter[data.gender.toUpperCase()].pants[0];

Answer №3

IF the item you have looks like this.

information: {
  "gender": "male",
  "myFilter": {
       "MALE": {
           "pants": ["33", "34"]
       },
       "FEMALE": {}
   },
}

In this case, (the gender value could be either "MALE" or "FEMALE")

Displaying on the console data.myFilter[gender.value].pants[0]);

Answer №4

Give this a shot to check its effectiveness

console.log(data.myFilter[data.gender.toUpperCase()]["pants"][0]);

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

Utilizing JavaScript event handlers on dynamically appended elements after the document has finished loading

One issue I am facing is with a javasript function that needs to change the value of an element appended after the document has loaded. The problem arises when trying to intercept actions on a newly appended DIV, such as: <div class="new-div"></d ...

`Multiple Autocomplete feature that allows rendering of previously selected items`

I've encountered a slight issue with my autocomplete feature. On the same page, I have two different autocompletes set up. Both of them pull elements via ajax from separate sources and use the _render option to display the items. The problem arises wi ...

Convert form data into JSON format while maintaining numerical values

One question that is frequently asked, but I have yet to find a solution for, is how to create a JSON body from a form in which the quotes are placed around the property names rather than the values. The desired JSON body should look like this: { "salary1 ...

What is the procedure for invoking a function when the edit icon is clicked in an Angular application

My current Angular version: Angular CLI: 9.0.0-rc.7 I am currently using ag-grid in my project and I encountered an issue when trying to edit a record. I have a function assigned to the edit icon, but it is giving me an error. Error message: Uncaught Re ...

Adding a type declaration to the severity property in React Alert - A guide to Typescript

I've developed a type declaration object for the incoming data, but no matter what I try to define as the type for the property "severity", it's not happy. The options it wants (as displayed below) don't seem feasible. I'm curious if th ...

What are the differences between using embedded documents and references in a mongoose design model?

I am currently in the process of developing a discussion forum using Node.js and mongoose. The structure I have in mind involves users being able to participate in multiple forums, with each forum containing multiple comments. Additionally, users should ha ...

Decoding JSON data

How do I parse 2 JSON objects? When AJAX returns just one object, it appears correctly: Object {32 : "Joseph"} However, when it returns more than 2 objects, this is what I get: ResponseText: "{"users":{"32":"Joseph"}}{"users":{"48":"Joseph K."}}" I h ...

Close the material-ui popper when clicking away

I am currently working on implementing a Material UI popper feature that should close when the user clicks outside of it using ClickAwayListener. However, I have been unable to make this functionality work despite trying different approaches. I've att ...

Is there a way for me to set distinct values for the input box using my color picker?

I have two different input boxes with unique ids and two different color picker palettes. My goal is to allow the user to select a color from each palette and have that color display in the corresponding input box. Currently, this functionality is partiall ...

Tips for formatting dates in Angular 6

I am currently working on a function that displays real-time dates based on user input. Currently, when the user enters the input, it is displayed in the front end as follows: 28.10.2018 10:09 However, I would like the date to change dynamically based on ...

Chrome mistakenly identifying octet-stream as a .png image

My application incorporates the use of Google Maps API V3 and ASP.Net, utilizing OverlayView to customize icons on the map. The icon's image is configured within the onAdd event by dynamically adjusting the background CSS property using JavaScript. T ...

Javascript code fails to execute properly on IE8

I have a scenario where I am working with two drop-down menus. When the user selects an option from one menu, it should dynamically change the options in the other menu. However, I'm facing an issue with Internet Explorer where the second drop-down me ...

Tips on handling multiple text field validation in material-ui for react?

Currently, I am working on developing a form using Material-UI and React.js where I need to validate two TextField components. My goal is to apply the same error and textHelper props to both TextFields. Below is a snippet of my code for reference. Any sugg ...

What is the Reason for Wrapping Masterpage Javascript File References in a PlaceHolder Control?

While examining the demo project for xVal, a validation framework designed for ASP.NET MVC, I observed that the Masterpage javascript references were enclosed in a PlaceHolder control: <asp:PlaceHolder runat="server"> <script type="text/javas ...

Creating a custom Chrome aesthetic, where are the hiccups occurring?

(I am a graphic designer/artist who is venturing into the world of code and scripts for the first time.) When working on my Chrome Theme code, an error cropped up: "Could not load extension from 'E:\Web\dev\theme\dev\Test& ...

The callback function fails to execute the click event following the .load() method

Hey there, I've hit a roadblock and could really use some help figuring out where I went wrong. Let me break down my script for you. On page1.html, I have a div that gets replaced by another div from page2.html using jQuery's .load() method. Here ...

What causes the sudden change in value of this array?

I can't seem to figure out what's going on with this question. It might be something silly, but I haven't been able to find any clues. Here is the array in question: const superVillains = [ { value: '1', label: 'Thanos&apo ...

Error in MEAN CRUD operation cannot be determined

{ text: undefined, done: false, _id: 529e16025f5222dc36000002, __v: 0 } PUT /api/todos/529e16025f5222dc36000002 200 142ms - 68b Encountering an issue while updating my CRUD todo list. Despite receiving a successful status code of 200 after submittin ...

cycle through several handlebars entities

Hey friends, I could really use your help right now. I'm attempting to iterate through these objects using handlebars. RowDataPacket { idUser: 1, username: 'xxxxxx', password: 'xxxxx', fullname: 'Julian Rincon'}, RowDat ...

What could be causing my application to hang on my local server?

Recently, I developed a NodeJS and Express MVC (or perhaps more accurately VC) app. Initially, everything worked smoothly until I integrated express-validator and included the middleware in the app file. This caused my localhost to freeze, displaying a GET ...