Is it feasible to simultaneously assign an object while destructuring a different one (all while utilizing defaults in the destructuring process)?

My ultimate objective is to effortlessly create a new object by utilizing the spread operator from an object that has been destructured while assigning default values, if they are absent.

It seems like achieving this goal might not be as straightforward as I had hoped. Here are my expectations and attempts:

// Initial object
const firstObj = {
  key1: "test1",
  key2: "test2",
};

// Desired end result
const finalObj = {
  key1: "test1",
  key2: "test2",
  key3: {
    nestedKey1: "nestedVal1",
  },
};

// Initial object
const secondObj = {
  key1: "test1",
  key2: "test2",
  key3: {
    nestedKey1: "actualValue",
  }
}

// Desired end result
const thirdObj = {
  key1: "test1",
  key2: "test2",
  key3: {
    nestedKey1: "actualValue",
  },
};

Snippet 1: Does not set default values.

const initialObject = {
  key1: "test1",
  key2: "test2",
}

const { ...newObject } = {
  key1,
  key2,
  key3: {
    nestedKey1: nestedKey1 = "nestedVal1",
  } = {},
  key4 = 'someDefault'
} = initialObject

console.log(newObject); // lacks key3 and key4
console.log(key4); // key4 exists as const, but key3 does not

Snippet 2: Functional, but may pose challenges with multiple levels of nesting.

const startingObj = {
  key1: "test1",
  key2: "test2",
}

let {
  key1,
  key2,
  key3: {
    nestedKey1: nestedKey1 = "nestedVal1",
  } = {},
} = startingObj

const key3 = startingObj.key3 || {};

const resultingObj = {
  key1,
  key2,
  key3: {
    ...key3,
    nestedKey1,
  }
}

console.log(resultingObj);

Snippet 2 (illustrating that nested objects remain untouched)

const obj = {
  key1: "test1",
  key2: "test2",
  key3: {
    someOtherKey: "itWorks",
  }
}

let {
  key1,
  key2,
  key3: {
    nestedKey1: nestedKey1 = "nestedVal1",
  } = {},
} = obj

const nestedKey3 = obj.key3 || {};

const newObj = {
  key1,
  key2,
  key3: {
    ...nestedKey3,
    nestedKey1,
  }
}

console.log(newObj);

Answer №1

Your confusion stems from the similarity between destructuring syntax and object declaration syntax.

For example, object declaration looks like this:

const a = {
  key1: "test1",
  key2: "test2",
}

Meanwhile, destructuring is demonstrated by:

const { key1, key2 } = a

console.log(key1)  // => test1
console.log(key2)  // => test2

It's important to note that the assignment operator = in JavaScript is right associative. Therefore, an expression like

let a = b = 1

means assigning the value 1 first to b, then to a.

Additionally, when you spread all values into a single variable, it's essentially a straightforward assignment using ES6 syntax. Thus:

const {...b} = a
// is equivalent to
const b = a

When you combine these effects, you achieve multiple assignment behavior:

const {...b} = a  
const {key1, key2} = a

Multiple assignments can be confusing, which is why there are linting rules in place to avoid such issues: https://eslint.org/docs/rules/no-multi-assign

Therefore, the answer to your question is simply, No! :)

It would require at least two lines for achieving that - one to gather properties with defaults during destructuring, and another to create the new object with those properties.

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

JavaScript's static function and variable that operate asynchronously

Encountering an issue with a "static" function in JavaScript (Node.js server). User.create = function(data, _callback){ var node = db.createNode(data); var _user = new User(node); _user.save(function(err){ if(err) return callba ...

Querying the field's object type in MongoDB

My database contains records with a field that has different data types in each record. I would like to query only for the records where this field contains strings. Is there a way to search for specific data types in this field? {"field1":ObjectId("53de" ...

When using the scrollHeight property of an iframe, it actually returns the height of the iframe

I'm having trouble obtaining the correct height of a page within an iFrame using scrollHeight. It seems to only return the height of the iframe itself, not the content inside. Despite trying various methods like scrollHeight, offsetHeight, and style. ...

What is the best way to load an ExtJS combobox with a JSON object that includes an array

After retrieving the following JSON from the backend: { "scripts": [ "actions/rss", "actions/db/initDb", "actions/utils/MyFile", "actions/utils/Valid" ], "success": true } The JSON data is stored as follows: t ...

Deriving variable function parameters as object or tuple type in TypeScript

Searching for a similar type structure: type ArgsType<F extends Function> = ... which translates to ArgsType<(n: number, s: string)=>void> will result in [number, string] or {n: number, s: string} Following one of the provided solu ...

What is the process for showing a button once a typewriter animation has completed?

Is there a way to implement a typewriter effect that types out a text line and then displays a button once the animation is complete? Here is the CSS code for the typewriter effect: .welcome-msg { overflow: hidden; /* Ensures the content is not revea ...

My Angular2+ application is encountering errors with all components and modules displaying the message "Provider for Router not found."

After adding routing to my basic app through app.routing.ts, I encountered errors in all of my test files stating that no Router is provided. To resolve the errors, I found that I can add imports: [RouterTestingModule], but is there a way to globally impo ...

Best practices for working with HTML elements using JavaScript

What is the best approach for manipulating HTML controls? One way is to create HTML elements dynamically: var select = document.getElementById("MyList"); var options = ["1", "2", "3", "4", "5"]; for (var i = 0; i < options.length; i++) { var opt = ...

Expanding the padding of the selected item to create more breathing room

Upon examining the following: https://jsfiddle.net/h8kmove5/27/ Let's say you select 9 at the bottom. The display shows 8 9 10. My intention is to create some additional space on either side of 9, or any other active item for that matter. This way, ...

Error: Attempted to export 'e', however it was not defined in the module (located at vite.js?v=d59cec13:236:3) - occurring in the three.js/vite combination

After dabbling in javascript, I decided to explore three.js and found it quite intriguing. However, after hours of setting everything up, I encountered a roadblock. When I attempted to create geometry and render it, the code stopped working. Upon investiga ...

Spin the mergeometry object around its center in Three.js

I've been struggling to figure out how to rotate the object at its center. Right now, I can rotate the scene but the object moves away from the user. I've tried looking at similar questions on forums, but haven't been able to make it work. B ...

Change the <base> element programmatically during server-side rendering

Searching for a way to obtain the base URL for an HTML page, so that relative URL requests from the browser utilize that base. If you are looking for answers, check out this link: Defining root of HTML in a folder within the site root folder When serving ...

Issue: Typescript/React module does not have any exported components

I'm currently facing an issue with exporting prop types from one view component to another container component and using them as state type definitions: // ./Component.tsx export type Props { someProp: string; } export const Component = (props: ...

Variations between <div/> and <div></div>

When using Ajax to load two divs, I discovered an interesting difference in the way they are written. If I write them like this: <div id="informCandidacyId"/> <div id="idDivFiles"/> Although both divs are being loaded, only one view is added ...

Discovering more about this topic

Looking for a way to create an expandable box that enlarges when "read more" is clicked, revealing text below it. And also looking to add a button that closes the expanded text back up. Experimented with the toggletext JavaScript command, as found on this ...

The Trouble with Vue.js 2 and Axios Scopes

I previously encountered this "problem" but can't recall the correct approach to achieve the desired results. My current setup involves using Vue 2 to load data into variables that are then displayed on the HTML side: window.Vue = require('vue&a ...

Performance Issues Arise with Rapid Clicking [jQuery]

Having trouble with a gallery script I created that includes thumbnails, a large image, and navigation arrows. When you rapidly click on thumbnails or arrows during the transition, it causes delays in the process. The more clicks you make, the more noticea ...

When anchor is set programmatically, the focus outline is not displayed

I am currently facing an issue with my application where I am programmatically setting focus on elements in certain scenarios. While it generally works well, I have noticed that when I set the focus on an anchor element using $("#link1").focus(), the focus ...

Utilize the _sortBy function from the lodash library to arrange an array based on a specific field

Looking at an array of objects similar to this: myArray = [ {AType: "aaa", Description: "De", …}, {AType: "bbb", Description: "Hi", …}, {AType: "ccc", Description: "Un", …}, {AType: "ddd", Description: ...

Issues with PhoneGap file upload functionality

For my first time using phonegap, I am trying to upload a simple image to my server. Following the Full Example in the documentation (), I can open the image gallery and select the image, but nothing gets uploaded to the server, and the success or failure ...