Handling undefined properties by defaulting to an empty array in ES6

In the code snippet below, I am attempting to extract barNames from an object named bar:

const {[id]: {'name': fooName} = []} = foo || {};
const {'keywords': {[fooName]: barNames}} = bar || [];
  • Please note that although fooName exists, it is not present as a property within keywords

My goal is to assign an empty array to barNames if fooName does not exist in bar.keywords. I have tried using the OR operator without success. I am looking for alternative solutions that do not involve additional ternary operators like ?, :, &&, etc.

Any tips or hints would be greatly appreciated.

Answer №1

It seems like you're in need of a default initializer:

const {[id]: {'name': fooName}} = foo || {};
const {'keywords': {[fooName]: barNames = []}} = bar || {};
//                                      ^^^^

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

Incorporate XHR into a JavaScript Function

Upon running the code below, a GET message is displayed in the Firebug Console. However, the variable appears as undefined, most likely due to its limited scope within the function. The objective here is to click on a table row, fetch relevant data from t ...

After reloading the data tables, analyze the information and dynamically highlight any rows in red that remain unchanged

I have a table that is refreshed every 5 minutes using ajax.reload(). One of the rows in this table is labeled as CIP. My goal is to highlight the CIP row on each refresh where the value remains unchanged from the previous value (value received in the la ...

Is your Angular5 service failing to transmit data?

I have two components in my code, A and B. Component A contains a form with data that I want to send to component B. However, it seems like component B is not receiving any data. Here is the code for Component A: import { MyService } from 'path/my ...

Discovering the current time and start time of today in EST can be achieved by utilizing Moment.js

Need help with creating Start and End Time stamps using Moment.js in EST: Start Time should reflect the beginning of today End Time should show the current time. This is how I have implemented it using moment.js: var time = new Date(); var startTime=D ...

Is it possible for me to utilize this code for logging in through a dialog box?

Here is the code snippet I have on the client side: <p>Username:</p> <p><asp:TextBox ID="tbUsername" runat="server"></asp:TextBox></p> <p>Password:</p> <p><asp:TextBox ID="tbPassword" runat="server ...

Display components created for children above the components created for parents

I am looking to render a component with a different route without it covering the entire page. For example, let's say I click on a question from a list on Stack Overflow, and then I want an animated modal to appear from right to left without changing ...

issues related to implementing search functionality with react-redux

Just starting out with my first react-redux project which is a list of courses, but I have hit a roadblock with redux. I am trying to implement a search functionality based on this answer, and while I can see the action in redux-devtools, it's not ref ...

Ways to serve JSON response following a 400 error code

After a user submits incorrect form details, such as an invalid username or blank email address, I make an Ajax request to my REST API. The response data I receive is structured as follows: HTTP 400 Bad Request Allow: POST, OPTIONS Content-Type: applicati ...

When an `angularjs select` is used with a filter, the first line may appear empty at first. However

I'm feeling a bit confused about why my ng-options is once again giving me an empty line with a filter applied. Could you please take a look at this plunker to see the issue? The goal is to show an org chart in a dropdown list that is based on a tre ...

I am unfamiliar with this specific JavaScript algorithm problem from Codewars

I need help with a JavaScript algorithm question This problem involves extracting two letters from the middle of odd-numbered characters My confusion lies in function getMiddle(s) { //Code goes here! let answer = ""; if (s.length % 2 !== 0) { a ...

What are some methods for transferring the state variable's value from one component to another in React?

I have the following scenario in my code: there is a Form.js component that interacts with an API, stores the response in the walletAssets state variable, and now I want to create a separate Display.js component to present this data. How can I pass the v ...

What methods can I use to streamline integration with minimal lines of code?

Seeking help with JavaScript: Recently dived into JavaScript and managed to create the desired functionality for my navigation menu. However, I suspect that my code is not optimized as I find myself repeating lines unnecessarily. Here's a snippet of ...

When attempting to fetch data with a dynamic URL in next.js, the error message "undefined is returned

While fetching data on my main page everything works as expected. However, when trying to fetch data in another folder using the same code but with a dynamic URL, I encounter an error when attempting to use methods on an array. Interestingly, when I consol ...

What is the impact of a floated element on vertical spacing?

I have come across an article discussing the usage of CSS, but I am puzzled as to why image number four is not positioned below image number one. Instead, it appears below image number three. Can someone please explain this to me? Here is the HTML code sni ...

Diving into Discord.JS - Is there a way to check if a specific message content exists within an array?

I'm currently working on developing a Discord user verification bot that generates a 2048-bit key upon joining a server. This key will be crucial for verifying your account in case it gets compromised or stolen, ensuring that the new account belongs t ...

The "main" entry for ts-node is not valid when running ts-node-dev

Recently, I embarked on a TypeScript project using yarn where I executed the following commands: yarn init -y yarn add typescript -D yarn tsc --init yarn add ts-node-dev -D Subsequently, I crafted a script titled dev that triggers tsnd src/index.ts, howev ...

The if-else condition is creating issues with the functionality of the buttons

Update #1 - Enhanced query, fresh functional link. Live site: The challenge at hand revolves around an if-else statement related to the form buttons on the right-hand column of the webpage. Scroll past the header and navigation to witness the issue in ...

Bring in Bootstrap and the Carousel plugin using Webpack Encore

Currently, I am tackling an issue within my Symfony project that involves Webpack Encore and the loading of Bootstrap and the Carousel plugin. The problem may stem from how I import Bootstrap, as it seems to partially work when I import the file like this ...

Link JSON in JavaScript using field identifiers

I've been working on incorporating JSON data into my JavaScript code, and the JSON structure I am dealing with is as follows: { "status":"ok", "count":5, "pages":1, "category":{ "id":85, "slug":"front-page-active", "title":"Front ...

Postman is showing an error when making a request using Express.js app.get()

Recently, I started working with Express.js and I am using Postman to test my API. When running the code below, I successfully retrieve all members from the object: // gets all members app.get('/api/members', (req, res) => { res.json(membe ...