What is the method for using the spread operator to add a property to an inner object in Typescript?

I have the following Object:

let car = { year: 2004, type: {name: "BMW"} }

Now, I am trying to add a property to the inner object "type". My aim is to achieve this using the spread operator as I require a new object due to the existing one being an immutable state object. The desired result should look like this:

{ year: 2004, type: {name: "BMW", model: "3er"}}

What would be the best approach to accomplish this task?

Answer №1

let vehicle = { year: 2018, brand: "Toyota" };
let updatedVehicle = {...vehicle, brand: "Honda", model: "Civic"};

Answer №2

Check out these examples:

(Not Mutable)

let vehicle = { year: 2004, type: {name: "BMW"} } // updated
Object.assign(vehicle.type, {model: "3er"});

console.log(vehicle)

(Immutable)

let car = { year: 2004, type: {name: "BMW"} } // remains unchanged
const updatedCar = Object.assign({}, car, {type:{...car.type, model: "3er"}});

console.log(updatedCar)

Answer №3

My goal was to introduce a new element into this intricate object structure.

const functionParams = {
    handler,
    runtime,
    environment: {
        variables: {
            restrictedActions: config.restrictedActions
        }
    }
}

I managed to do it in the following way:

const newFunctionParams = {...functionParams, environment: {
    ...functionParams.environment, variables: {
        ...functionParams.environment.variables,
            APIAllowEndpoint: `https://severless....`,
            APIDenyEndpoint: `https://severless....`,
            TOPIC: topicArn
    }
}}

The outcome:

{
    handler,
    runtime,
    environment: {
        variables: {
            restrictedActions: config.restrictedActions,
            APIAllowEndpoint: `https://severless....`,
            APIDenyEndpoint: `https://severless....`,
            TOPIC: topicArn
        }
    }
}

Credit goes to @chelmertz

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

Utilize jQuery to showcase elements in a dropdown menu

Hey everyone, I'm working on an ASP.NET MVC4 project and I'm using a jQuery script on the edit page. However, I am encountering an issue with displaying elements on the page. Here is the initial HTML markup of my dropdown before any changes: & ...

Retrieving the Vue component object while inside the FullCalendar object initialized within the component

When using Full Calendar with VueJS, I ran into a problem where I needed to open a custom modal when clicking on a time slot in the calendar. The issue was that I couldn't call a function outside of the Full Calendar object to handle this. This is bec ...

Use JavaScript to gather various data forms and convert them into JSON format before transmitting them to PHP through AJAX

My understanding of JSON might be a bit off because I haven't come across many resources that discuss posting form data via JSON/AJAX to PHP. I often see jQuery being used in examples, but I have yet to delve into it as I've been advised to firs ...

Requests exceeding 8 kilobytes

I am looking to measure the round trip time between a client and server. Users have the option to determine the size of the request/response message they want to send. On the client side, I am using the Ajax-Post method to transmit 100 messages every 100 m ...

Strategies for splitting a component's general properties and accurately typing the outcomes

I am attempting to break down a custom type into its individual components: type CustomType<T extends React.ElementType> = React.ComponentPropsWithoutRef<T> & { aBunchOfProps: string; } The code appears as follows: const partitionProps = ...

What is the best way to assign a unique name to a dynamically generated text box using jQuery

In an effort to name a dynamically created textbox based on a specific event, I attempted the following code. The function GenerateTextBox was intended to assign a name and value of "" to the textbox upon generation, however, the name did not get assigned ...

The specified 'contactId' property cannot be found within the data type of 'any[]'

I am attempting to filter an array of objects named 'notes'. However, when I attempt this, I encounter the following error: Property 'contactId' does not exist on type 'any[]'. notes: Array < any > [] = []; currentNot ...

Removing white space between words in Angular component HTML files using TypeScript

Within my component.html file, I am utilizing an img tag with the image source value originating from an array. This array contains a property known as "name", which may consist of two or three words separated by spaces. How can I adjust the image src to m ...

I encountered an error in my Rails 4 project where I got a NoMethodError stating "undefined method `id' for nil:NilClass" in my create.js

When I click a button, I'm attempting to display a partial. It seems like I am making an obvious mistake... and I suspect it's not related to the following code snippet: $('#modrequest').empty(); $('#modrequest').html("<%= ...

Creating dynamic div elements with a button click in JavaScript / jQuery

Hey, do you know how to dynamically add a div when a button is clicked using JavaScript/jQuery? I want the added div to have the same formatting as the div with the class "listing listing_ad job". Here is the code I have tried using jQuery: $('#bt ...

Is it possible to detect the source of a digest cycle in AngularJS?

I've found myself knee-deep in a legacy AngularJS project lately. The codebase is quite intricate and expansive, making it difficult to showcase here. However, I've come across an issue where functions triggered during digest changes are firing h ...

What is the best method for showing information beneath each tab?

Here is my CodePen link: https://codepen.io/santoshch/pen/MWpYdXK .tab1border{ border-right: 2px solid #f0f0f0; } .tab2border{ border-right: 2px solid #f0f0f0; } .tab3border{ border-right: 2px solid #f0f0f0; } .tab4border{ border-right: 2px soli ...

Encountering net::ERR_SSL_PROTOCOL_ERROR while trying to access the Nextjs dev server using an IP address

Upon running my Nextjs project with npm run dev, I encountered an issue while accessing the app via http://localhost:3000. The resources were loaded using the HTTP protocol, such as http://localhost:3000/js/dmak_normal.js. However, when attempting to acce ...

Beginner in html, css, and javascript: "Tips for saving jsfiddle demos?"

Recently, I developed an interest in JavaScript and CSS and came across some impressive examples on jsfiddle. I was wondering if there is a way to "export" these examples to my computer. Simply copying and pasting doesn't seem to work. How can I modi ...

Issue with the Core php code - In relation to the onclick and onload events

The code below is currently functioning correctly: <a href ="#" onclick="accept ("<?php echo $getservice [$i]['id']; ?>, document.frml)"> Accept </a> In the above code, a Javascript function is being ca ...

Examining Angular Modules using Jasmine Unit Tests

Currently, I am integrating an AngularJS service into my application. Upon testing, I discovered that the service is not as reliable as I had hoped. To address this issue, I decided to implement some unit tests for it. While the service functions properly ...

Why isn't my jQuery second click toggle functioning properly?

http://jsfiddle.net/motocomdigital/uTV5k/18/ I have recently made changes to use toggle instead of click, but I am still facing difficulties with smooth transitions. This code includes a combination of javascript and jquery. My goal is to create an anim ...

Implementing Fullpage.js with persistent elements throughout slides

Can I keep certain elements fixed between slides? I found that the only way to accomplish this was by placing the text element outside of the slide div. <div class="section" id="section1"> <div class="intro"> <h1> ...

In a Javascript scenario, only the initial button can successfully submit to an Ajax form even when having unique

Similar issues have been reported by other users when looping rows of buttons, often due to inadvertently reusing the same Id or value. I am facing a similar issue, but each of my buttons is unique. AJAX request <script> $(document ...

Having trouble coordinating a mongoose action to retrieve an array

Within the management of an employee app, I aim to segregate the business logic database operations from the main application file. A straightforward operation involves retrieving all employees from the database by using async/await for synchronization: m ...