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

What is the best way to transfer an array made in JavaScript to a different JSP and subsequently utilize that array in a Java function within that JSP?

I have a script that needs to pass an array called "playernames" to a Java function on another .jsp. I'm looking for guidance on how to send this array to the other page and then retrieve it for my Java function. <script> function getPlayerName ...

tips for transitioning between various json entities

Recently, I created a login page code using JavaScript that runs on a Node Express.js server. Users can input their username/email and password, and all the data gets stored in a JSON file structured like this: {"username":"admin"," ...

Trouble with displaying an array of React elements in the render() function

While learning React by creating sample projects with Meteor, I've managed to grasp the basics but hit a wall. I'm utilizing a Twitter API to fetch the latest three tweets from the BOINGBOING Twitter page. The API is functional, and I can succes ...

Creating beautifully formatted PDFs using pdfmake in AngularJS

I have a HTML popup displaying data retrieved from the server, and I am attempting to download this data as a PDF using the pdfmake plugin. While I am able to generate the PDF file, the challenge lies in replicating the HTML page layout in the PDF. Here is ...

How can I retrieve the array data that was sent as a Promise?

I have a database backend connected to mongoDB using mongoose. There is a controller that sends user data in a specific format: const db = require("../../auth/models"); const User = db.user const addProduct = (req, res) => { User.findOne({ ...

Using PHP cURL to send an oauth2.0 access token in the header and making a POST request with JSON

My goal is to send an access_token to oauth2.0 in the POST header, while also POSTing JSON data in the body. I have obtained my access_token and now want to use it to submit some information to the API. $token = array( "access_token" =>$test->acce ...

Performing a MongoDB query in a controller using the MEAN stack with Node.js

My goal with this controller is to retrieve all the results of a collection. Despite having one item in the prop collection, I am encountering an undefined error. Error: Cannot call method 'find' of undefined This snippet shows my server.js fil ...

A guide on utilizing URL parameters in Express.js to deliver images as static files

Looking to dynamically serve images from an "images" directory in my project based on user input, how can I achieve this? For instance, https://localhost:3000/images?fileName=burger This URL should display the corresponding image in the browser. If any ...

angular primeng table has a checkbox to select all checkboxes

Is there a way to check all checkboxes in a table when the checkbox in the table header is clicked? I am currently utilizing angular 12 and primeNG table for this functionality. <p-table styleClass="text-sm" [value]="value" [loading] ...

Using a for loop in JavaScript to fetch and display a specified number of results from an API

Recently, I delved into the world of Javascript and API arrays to grasp the concept of retrieving and manipulating various APIs. The topic of Javascript loops and arrays has been discussed numerous times, both here on StackOverflow and on other platforms. ...

What is the best way to redirect a URL to include www using Node.js?

What is the best way to redirect a URL to start with www? For instance: ---> ...

Is there a way to use JavaScript to modify the position of a div element

Can we adjust the div position using CSS (absolute or relative) with JavaScript? Here's an example code snippet: <div id="podpis" style="margin-top: 2rem;"> <div class="invoice-signature"> <span><?=$xml->sanitiz ...

Steps for removing the label associated with an input field in an HTML form

I attempted to use JQuery and JavaScript in order to modify the CSS of a label to make it greyed out, but unfortunately I have not been able to achieve this. The label is positioned next to a checkbox, and although I am able to disable the checkbox, I hav ...

Cloud function for Firestore to recursively update a subcollection or collection group

I've been working on this cloud function: import pLimit from "p-limit"; const syncNotificationsAvatar = async ( userId: string, change: Change<DocumentSnapshot> ) => { if (!change.before.get("published") || !change.after.exists) { ...

I am looking to eliminate the double quotation marks from a JSON file so that I can properly utilize

How can I successfully save a JSON return into an NSDictionary when there are spaces and double quotes present in the data? Is it possible to parse SBJSON to remove the double quotes before saving to rowsArray? rowsArray: { Rows = ( { ...

Ensure to verify the dimensions and size of the image prior to uploading

Is there a way to check the dimensions of an image using this function? I want to verify it before uploading... $("#LINK_UPLOAD_PHOTO").submit(function () { var form = $(this); form.ajaxSubmit({ url: SITE_URL + 'functions/_app/execute ...

Angular not firing slide.bs.carousel or slid.bs.carousel event for Bootstrap carousel

I've searched high and low with no success. I'm attempting to detect when the carousel transitions to a new slide, whether it's automatically or by user click. Despite my numerous attempts, I have been unable to make this event trigger. I ha ...

Using Three.js to create a React button positioned above a canvas

Here's the code I have written using three.js in a React component. I am looking to add a button above the canvas. How can I achieve this? Additionally, I would like to know how to add a click event on objects rendered in three.js. import React, { Com ...

Monitor the collection for changes before adding an item to the collection

When using ui-select multiple, I am facing an issue where I need to check the collection before ng-model="collection" is updated in order to ensure that the new value is not already present in it. Simply watching the collection does not solve this problem ...

When attempting to read a Json file with Pyspark, the error message "Unable to find '`keyName_1`' in the provided columns: [keyName_1, keyName_2, keyName_3]" is displayed

Currently, I am utilizing pyspark to read data from a JSON file. The process involves the following steps: raw = sc.textFile(path) dataset_df = sqlContext.read.json(raw) In order to extract specific keys from the JSON file (if those keys are present), I ...