Extending a Sub-Object in JavaScript

I'm attempting to include new attributes to the sub-object within object1. However, I am facing issues with it being overwritten.

const object1 = {
  a: 1,
  b: 2,
  c: 3,
  sub: {
    e: 1,
    f: 2
  }
};

const object2 = Object.assign({
  j: 4,
  m: 5
}, object1.sub);

console.log(object2);

Answer №1

One useful tip is to consider rearranging the parameters for Object.assign so that the target comes first.

const object = { a: 1, b: 2, c: 3, sub: { e: 1, f: 2 } };

Object.assign(object.sub, { j: 4, m: 5 });

console.log(object);

Answer №2

Using the new ES6 syntax:

const firstObject = { x: 10, y: 20, z: 30, inside: { p: 10, q: 20 } };
const secondObject = {...firstObject, inside: {...firstObject.inside, r: 40, s: 50}}
console.log(secondObject)

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

Altering the context of Javascript script execution

I needed to switch the JavaScript execution context from the parent window to the child window. I was able to successfully load my script objects and functions into the child window context, however, I encountered difficulty in making third party libraries ...

Is it possible to conceal the source code within the dist js file using Vue JS?

I am looking to create a detailed logging page that showcases the logs without revealing the specific type of logging. I want to prevent users from accessing the minified vue JS script and easily reading the logged information. Is there a way to implemen ...

Update the observability status of one observable using a different observable

Upon running the following code, you'll notice that an xhr request is being sent to the console regardless of whether I am subscribed to the subject or not. I would prefer for these requests not to be made if I am not subscribed. // To start, install ...

Transforming a React application from ES6 hooks to Class-based components

Hello, I am new to React and currently facing a challenge in converting the following code into a Class Based Component. Despite knowing that I am going in the opposite direction, I am unable to figure out how to proceed without encountering errors. Any ...

initiate a POST request using fetch(), where the data sent becomes the key of

Encountered an issue with sending a POST fetch request where the JSON String turns into the Object Key on the receiving end, specifically when using the { "Content-Type": "application/x-www-form-urlencoded" } header. I attempted to use CircularJSON to res ...

Toggle element visibility upon clicking

<table id="selectsupp"> <tr> <td> <select id="category"> <option value="display" readonly="true">-Shop By Category-</option> <option value="all">All</option> <option val ...

Can you please explain how I can retrieve information from a Firebase collection using the NextJs API, Firebase Firestore, axios, and TypeScript?

I'm currently utilizing api routes within NextJS 13 to retrieve data from Firebase. The code for this can be found in api/locations.tsx: import { db } from "../../firebase"; import { collection, getDocs } from "firebase/firestore"; ...

Issues encountered with Nextjs 13.4 and Next-Auth 4.2 regarding the signIn("credentials", { }); functionality not functioning as expected

When using next-auth credentials in my current project, I encountered an issue with the signIn() function from next-auth/react. It appears that the redirection to the admin page persists regardless of whether the login details are correct or not. {error: n ...

Resource for building user interface components in Javascript

I need assistance with implementing a feature that involves scrolling through different text blocks and corresponding images. Users should be able to select a specific text block and have the associated image on the right scroll into view, similar to a car ...

Using Jquery to insert error messages that are returned by PHP using JSON

I am attempting to utilize AJAX to submit a form. I send the form to PHP which returns error messages in Json format. Everything works fine if there are no errors. However, if there are errors, I am unable to insert the error message. I am not sure why th ...

Save information on users' Google accounts

Utilizing this resource, I successfully implemented a login feature on my website. The implementation includes functions such as onSignIn, signOut, and auth2.isSignedIn.get() to manage user authentication. Now, I am looking for a way to extract specific d ...

Exploring the power of makeStyles in Material UI when combined with TypeScript

I am currently in the process of converting a JavaScript template to Typescript. Here is an example of my accordionStyle.ts file: import { primaryColor, grayColor } from "../../material-dashboard-pro-react"; const accordionStyle = (theme?:an ...

What is the best way to share information among Vue3 single file component instances?

I am seeking a way to have certain data in my single file component shared among all instances on the page, similar to how static variables work in PHP/C. To achieve this, I understand that in single file components, we declare data as a function like so: ...

Is there a way to automatically populate textbox values using a MySQL query response when the dropdown selection is changed?

How can I make the fields customer_address, customer_city, customer_state, and customer_zip autofill upon changing the selection in the dropdown for customer_name? I've searched everywhere but cannot find a solution. Your assistance would be greatly ...

Transform JSON reply in JavaScript/Typescript/Angular

Looking for assistance with restructuring JSON data received from a server API for easier processing. You can find the input JSON file at assets/input-json.json within the stackblitz project: https://stackblitz.com/edit/angular-ivy-87qser?file=src/assets/ ...

Article: Offering CoffeeScript and JavaScript Assets Simultaneously

Currently, my web app is up and running using Node and Express. I initially developed it in JavaScript but now want to transition over to CoffeeScript. My goal is to have both file1.js and file2.coffee coexisting in the application (with both being served ...

Issue with useEffect EventListener in REACT HOOKS

Recently, I attempted to create a simple Snake-Game using REACT. Everything was going smoothly until I encountered an issue with using useEffect for moving the "snake" when a keydown event is triggered. The challenge arose when trying to implement moveSnak ...

Seeking the perfect message to display upon clicking an object with Protractor

Currently, I am using Protractor 5.1.1 along with Chromedriver 2.27. My goal is to make the script wait until the message "Scheduling complete" appears after clicking on the schedule button. Despite trying various codes (including the commented out code), ...

button that takes you back to the top of a mobile website

I want to customize the Scroll To Top button so that it only appears once the user begins scrolling down, rather than always being visible even when at the top of the page. Just a heads up, I don't have much experience with JavaScript, so I might need ...

Manage numerous canvas animations

Is there a way to interact with an already drawn Canvas animation? I am attempting to create 3 distinct tracks that can be controlled by a "Start" and "Stop" button. However, when I click the Start button on the first canvas, it triggers the last canvas in ...