Exploring the Depackaging of ES6 Nested Objects

How can I implement ES6 with Destructuring to give users options? I'm having trouble dealing with nested objects and preventing the defaults from being overwritten by partial objects.

Check out this simple example on MDN:

function drawES6Chart({size = 'big', cords = { x: 0, y: 0 }, radius = 25} = {})
{
  console.log(size, cords, radius);
  // perform some chart drawing
}

drawES6Chart({
  cords: { x: 18},
  radius: 30
});

The result displayed is

big {"x":18} 30

but what I actually want to see is

big {"x":18,"y": 0} 30

The provided cords object is incomplete and removes the default y value. My goal is to retain any value that is not explicitly replaced.

Answer №1

To properly destructure the coords object and assign default values to its x and y components, you should do so individually:

function drawES6Chart({size='big', cords: {x=0, y=0} = {}, radius=25} = {}) {
    const coords = {x, y}
    console.log(size, coords, radius);
}

Your initial approach would only set default values if no cords object was provided at all.
You were on the right track with using the complete options object pattern, where the default value is an empty object - instead of this incorrect syntax:

function drawES6Chart({size, cords, radius} = {size:'big', cords:{x:0, y:0}, radius:25}) {
    // not working

Answer №2

Providing defaults for the main options object is feasible (as you are doing), however, it is not possible to do so directly for nested objects within it.

I personally appreciate bergi's response, but as Paul mentioned, it explicitly defines the symbols x and y inside the function.

If this isn't desired, an alternative approach would be to use Object.assign within the function:

cords = Object.assign({}, {x: 0, y:0}, cords);

Though it may have a resemblance to ES5...

To prevent redundancy, you can store the defaults in a variable: (live copy on Babel's REPL)

let cordsDefaults = {x: 0, y: 0};
function drawES6Chart(
  {size = 'big', cords = cordsDefaults, radius = 25} = {}
  )
{
  cords = Object.assign({}, cordsDefaults, cords);
  console.log(size, cords, radius);
  // do some chart drawing
}
drawES6Chart({cords: {x:18}});

Result:

big {"x":18,"y":0} 25

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

Fade out when the anchor is clicked and fade in the href link

Is it possible to create fade transitions between two HTML documents? I have multiple HTML pages, but for the sake of example, let's use index.html and jobs.html. index.html, jobs.html Both pages have a menu with anchor buttons. What I am aiming to ...

"Encountering a strange issue where submitting a form with Jquery and AJAX in Rails does not work as expected, causing the index

Currently facing a unique issue with a jQuery/Ajax HTML update form. The application in question is a single-page TODO App that utilizes a Rails controller, where all changes to the DOM are made through jQuery/Ajax. After rendering the TODOs on the page v ...

Ensure that an input field on the PHP form is required

Currently working on a form with multiple input fields. I'm wondering if there's a way to prevent the form from being submitted to the server if a specific field is left empty. I'd like to use a JavaScript pop-up box to notify the user inst ...

JavaScript function to provide a range of numbers based on a specified number and step value

I am looking for a solution to dynamically generate content based on the number of slides/steps using JavaScript. Any suggestions on how to best achieve this? Thanks in advance! switch(this.currentSlide) { case 1: return '1-12'; ...

Utilizing database information to dynamically select Nightwatch.js tests for execution

Currently, I am in the process of configuring nightwatch tests for a specific website. The setup involves assigning testing personas to run tests, which works smoothly in our development environment. However, we face an issue when we need to dynamically ad ...

Is it possible for a search box selection toggle to reveal a hidden information box underneath it containing all the compiled data?

Improve the user experience on my website by implementing a search feature for US states and Canadian territories. When visitors type in their selection, I want them to be able to click on an icon that will reveal relevant information about that choice. T ...

How to retrieve an element using a dynamically generated class name in Vue.js

<v-data-table :headers="menuheaders" //this menus from api response :items="menus" item-key="usersmenu_menuid" items-per-page="1000" hide-default-footer="" class="elevation-1" > <template v-s ...

Tips on customizing the appearance of JavaScript output?

I recently created a plugin for my website with JavaScript, and one of the lines of code I used was output.innerHTML = "Test"; Is it possible to apply CSS styles to this element, or is there an alternative method? ...

stop all HTML5 videos when a specific video is played using jQuery

I am facing an issue with 10 HTML5 videos on the same page, CHALLENGE Whenever I click on different videos, they all start playing simultaneously... <div><video class="SetVideo"></video><button class="videoP"></button>< ...

Google Maps introduces a new feature that creates a blur effect on

Currently, I am utilizing the sample code provided below to superimpose an element on a Google map. <!DOCTYPE HTML> <html> <head> <title>Google Map Test</title> <style> html, body { margin: 0; ...

How to Handle Jquery POST Data in Express Servers

Update Make sure to check out the approved solution provided below. I ended up fixing the issue by removing the line contentType: 'appliction/json', from my POST request. I'm facing a problem trying to send a string to Node.js/Express becau ...

What is the best way to deliver flash messages using Express 4.0?

Currently, my web application requires authentication, and I am encountering an issue with the signup page. If a user tries to sign up with an email that is already in the database, I want to display an error message. Here is the code snippet I am using on ...

Issue: [ng:areq] The parameter 'PieController' is not properly defined, it is currently undefined

Why am I getting an error when using ng-controller='DoughnutCtrl' in a dive? Error: [ng:areq] Argument 'DoughnutCtrl' is not a function, got undefined Here is my Chart.js code: 'use strict'; angular.module('portfoli ...

To begin utilizing Node.js modules, you must use the `#` symbol as the starting point

Quoting the Nodejs documentation, available at this link require(X) from module at path Y 1. If X is a core module, a. return the core module b. STOP 2. If X begins with '/' a. set Y to be the filesystem root 3. If X begins with './ ...

Different ways to manipulate the CSS display property with JavaScript

Having trouble changing the CSS display property to "none" using JavaScript. Check out my code: <div class="mydiv" onClick="clickDiv1()">hello</div> <div class="mydiv" onClick="clickDiv2()">hi</div> <div class="mydiv" onClick=" ...

Leveraging variables from views.py in JavaScript

My approach to populating a user page has evolved. Initially, users would choose a value from a drop-down and an AJAX call would retrieve data. Here is the code that was functioning: HTML: <h3>Experimenter: {{ request.user }}</h3> <h3>R ...

Trouble with jQuery event.keyCode in detecting alphanumeric characters

I recently developed a script that is supposed to detect the key the user clicks and perform an action based on whether it is alphanumeric. However, I am encountering an issue as the script does not seem to be working as expected, and I am not receiving an ...

Using React to access the properties of objects within an array that has been dynamically mapped

For my initial dive into developing a React application, I am currently in the process of fetching data from a database and updating the state to store this information as an array. My main challenge lies in accessing the properties of the objects within t ...

The problem with Ajax POST is occurring in Firefox and Chrome, but not in IE8

I am encountering an issue with the code snippet provided below. Upon executing it in Internet Explorer 8, I receive an alert when the call is successful. However, this behavior does not occur in Firefox and Chrome. In other words, there is no alert disp ...

Interact with HTML Radio Buttons to Trigger Input Opening

I need to have a message saying "We're sorry..." and a "black box" displayed only when the radio button is set to YES, otherwise keep it hidden. Can I achieve this using JavaScript only, or is there a way to do it with HTML alone? <h3 >Did you ...