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 03 Answers
Reset to default 5const 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条)