简体   繁体   中英

How can i add a property to an inner Object in Typescript with spread operator?

I have following Object

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

Now i want to add a property to inner object "type". I want to to this with the spread operator, since i need a new object, because the existing is an immuteable state object. The result should be:

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

How can i do this?

const car = { year: 2004, type: {name: "BMW"} };
const modifiedCar = {...car, type: {...car.type, modell: "3er"}};

Try this :

(Not Immutable)

 let car = { year: 2004, type: {name: "BMW"} } // changed Object.assign(car.type, {modell: "3er"}); console.log(car) 

(Immutable)

 let car = { year: 2004, type: {name: "BMW"} } // still the same const result = Object.assign({}, car, {type:{...car.type, modell: "3er"}}); console.log(result) 

I wanted to add another variable to this object which as you can see is deeply nested.

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

I achieved it like so:

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

The result:

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

Credit to @chelmertz

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM