Unusual deconstructing assignment leading to an undefined result


const apiConfig = JSON.parse(process.env.apiConfig);
const securityContextConfigurations = _.get(
  apiConfig,
  'agpAPIs',
  {});

// What exactly is happening here?

const {
  securityContext : { apiKey, securityType }
} = securityContextConfigurations;

// What is the purpose of this block?
// There seems to be an issue where securityContext always returns undefined even though there is data in securityContextConfigurations object

const securityContext = { apiKey, securityType };
const { serviceContext } = apiConfig;
serviceContext.refID = v5(serviceContext.refID, v1());
return Promise.resolve({ securityContext, serviceContext });

The securityContextConfigurations object contains the key value pairs I need for securityContext, but my code fails at creating the securityContext object.

This pattern is unfamiliar to me and I am exploring ways to simplify it.

Answer №1

Understanding a More Complex Form of Destructuring Assignment

If you're familiar with the simpler version, this one adds an extra layer to it.

const a={b:3, c:"hello"}

const {b, c} = a

console.log("b is ",b)
console.log("c is ",c)

The code snippet above showcases how to further destructure objects in JavaScript.

const securityContextConfigurations = {
  securityContext: {
    apiKey: "hello",
    securityType: "high"
  }
}

const {
  securityContext: {
    apiKey,   
    securityType
  }
} = securityContextConfigurations;

// Extracting variables from nested objects

console.log("apiKey is", apiKey)
console.log("securityType is", securityType)
// Note that "securityContext" itself is not extracted as a variable

To simplify understanding, let's break down what's happening step by step using different variable names on each side of ":".

const securityContextConfigurations = {
  securityContext: {
    apiKey: "hello",
    securityType: "high"
  }
}

const {
  securityContext: {
    apiKey:x,   
    securityType:y
  }
} = securityContextConfigurations;

// Right variable name after ":" will be used for extraction. Left variable name simply indicates element of source object to extract.

console.log("x is", x)
console.log("y is", y)

// apiKey, securityType and securityContext are not extracted directly as variables.

Even seasoned JS developers may find this syntax unfamiliar, but it serves a specific purpose in extracting only desired elements.

Deciphering the Programmer's Intention

In this case, the goal was likely to isolate specific properties before combining them into a new object named securityContext.

The original code retrieves only apiKey and securityType, then reconstructs a new object with those key-value pairs.

Although a more straightforward approach would be direct extraction of securityContext followed by isolating the required items, this method ensures exclusion of any unwanted elements.

Perhaps the intention was to avoid inadvertently including other parts of securityContext, explaining the intricate process employed.

Simplified Alternative Implementation

const apiKey = securityContextConfigurations.apiKey
const securityType = securityContextConfigurations.securityType
const securityContext = { apiKey, securityType };

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

Generating a UTC timestamp in TypeScript

I am currently facing an issue with my application where I need to ensure that it always uses UTC time, regardless of the system time. I have a method in place to create a date: public static createDate(date: Date = new Date()): Date { return new Dat ...

The output of the incorrect .bind() example is not as

I recently came across the .bind() method while learning JavaScript. The example I found on MDN here was quite helpful, but I decided to add some console.log() statements for better understanding. this.x = 9; // Here 'this' refers to the glob ...

Adjust the Highcharts semi-pie design by eliminating the gap between the pie and the legend

I'm having trouble adjusting the spacing between the bottom of a semi circle donut chart in Highcharts and the legend below it. Despite my efforts, I have not been successful in reducing this gap. Here is the basic chart I am currently working on: h ...

Height of VUE Carousel 3D Slider dimension

I recently integrated the VUE Carousel 3D Slider on my website, but I'm facing an issue with controlling the height of the slides. There seems to be excessive space below the slider because the slides are unnecessarily tall. I attempted to adjust the ...

"Utilizing Javascript to create a matrix from a pair of object arrays

Attempting to transform an infinite number of arrays of objects into a matrix. height: [1,3,4,5,6,7] weight: [23,30,40,50,90,100] to 1 23 1 30 1 40 1 50 ... 3 23 3 30 3 40 ... Essentially mapping out all possible combinations into a matrix I experime ...

Prevent title flickering in Android using Ionic

I am attempting to create a tab content page using the "standard" method recommended by the ionic template example. However, I have noticed that when switching between tabs on Android, the view title flickers. This issue is not present on iOS or desktop b ...

Incorporating a mat-expansion-panel component into a mat-accordian

I'm trying to integrate a mat-expansion-component into a mat-accordion, but I'm facing styling issues. <mat-accordion> <app-panel1></app-panel1> <app-panel2></app-panel2> </mat-accordion> The app-panel ...

Creating an expand and collapse animation in a `flex` accordion can be achieved even when the container size is fixed using

Good day, I am in need of a fixed-height HTML/CSS/JS accordion. The requirement is for the accordion container's height to be fixed (100% body height) and for any panel content overflow, the scrollbar should appear inside the panel's content div ...

What is the reason behind every single request being treated as an ajax request?

Recently, I embarked on a new application development journey using rails 4.0. However, I've encountered an unexpected situation where every request is being processed as an ajax request. For instance, consider this link: =link_to "View detail", pr ...

The Vuetify v-img component is failing to render on the screen

I am facing an issue with this code snippet as the image is not being displayed. I have double-checked the path to the image and everything seems to be correct. I am unable to figure out what the problem is, as everything looks clear in the console. <v- ...

Different approaches for expanding object.prototype while utilizing jQuery

Once upon a time, I made the mistake of trying to extend Object.prototype and ended up encountering errors in my jQuery file. After doing some research, I found out that extending Object.prototype is frowned upon in the JavaScript community due to potentia ...

Utilizing the loop counter within an Array

Currently, I am attempting to iterate through numbers 1 to 21 and then utilize those numbers in order to obtain an Array of Strings like ['e1.wkh',...'e21.wkh']. However, at the moment I am only receiving the value ['e21.wkh'] ...

Cypress: measuring the size of a hidden array

Embarking on a lengthy journey here, so bear with me. TL:TR I've recently delved into learning Cypress and encountered an issue. I'm dealing with a highly dynamic list that sometimes may have zero elements. I need to determine its length for cer ...

Customize radio buttons in React using React Hook Form. Personalize the

I am currently working on a form using react-hook-form to update data with two radio options. The form is able to read and display the data correctly, however, when I try to change the value, the interface does not update accordingly. Can anyone help me id ...

Choosing the right jQuery selector to target a section that contains div elements

Whenever the h2 element within a section is clicked, I want all the fields in that section to be displayed. For example, if the user clicks on 'Contact Information', the three form inputs (fields) below the Contact Information heading should appe ...

Is there a way to modify the domain of an iFrame's scr based on the parent window's URL?

Is there a way to dynamically change the scr="" attribute of an iFrame based on the current URL of the window? The goal is to have different values for the scr attribute depending on the parent window's URL. For example, if the parent window's UR ...

Attempting to eliminate annoying alternative text from the lightbox photo gallery

My collection of artwork can be found on my website www.unlicensedeyesurgery.com. However, I am facing an issue with the Lightbox code that is being used. The problem lies in the fact that the Lightbox code utilizes the rel attribute of the anchor tag to d ...

Tips for modifying a nested reactive form while ensuring validation is maintained?

When retrieving data from a service in the form of an array, one might wonder how to bind this data in a nested form if there are potentially endless entries in the array. The form is expected to be pre-filled with this data, including validation for each ...

Steps for including a variable in a textarea within a MERN stack

In the process of developing my MERN application, I have integrated a textarea feature. I am interested in allowing users to dynamically insert variables within the text template. For example, enter image description here Can anyone provide guidance on ho ...

What are the steps to successfully launch a basic Node.js API?

#index.js const express = require('express'); const app = express(); const fs = require("fs"); app.get('/listUsers', function (req, res) { fs.readFile( __dirname + "users.json", 'utf8', function (err, d ...