0

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?

chelmertz
  • 20,399
  • 5
  • 40
  • 46
Emre Öztürk
  • 2,660
  • 4
  • 16
  • 19

3 Answers3

5
const car = { year: 2004, type: {name: "BMW"} };
const modifiedCar = {...car, type: {...car.type, modell: "3er"}};
chelmertz
  • 20,399
  • 5
  • 40
  • 46
1

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)
Ghoul Ahmed
  • 4,446
  • 1
  • 14
  • 23
0

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

djsd123
  • 383
  • 1
  • 4
  • 8