javascript - How can i add a property to an inner Object in Typescript with spread syntax? - Stack Overflow

I have following Objectlet car = { year: 2004, type: {name: "BMW"} }Now i want to add a prop

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 syntax, since i need a new object, because the existing is an immutable state object. The result should be:

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

How can I do this?

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 syntax, since i need a new object, because the existing is an immutable state object. The result should be:

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

How can I do this?

Share Improve this question edited Oct 22, 2024 at 10:47 VLAZ 29.2k9 gold badges63 silver badges84 bronze badges asked Jun 13, 2019 at 11:15 Emre ÖztürkEmre Öztürk 2,8704 gold badges19 silver badges19 bronze badges 0
Add a ment  | 

3 Answers 3

Reset to default 5
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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745404380a4626247.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信