Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
187 views
in Technique[技术] by (71.8m points)

javascript - Using spread operator to update an object value

I have a function which adds a key to incoming object, but I have been told to use spread operator for that, I have been told that I can use the spread operator to create a new object with the same properties and then set isAvailable on it.

  return new Partner(ServerConfig, capabilities, initialState)
}

class Partner {
  constructor (ServerConfig, capabilities, initialState) {
    initialState.isAvailable = true

So I tried something like this but coulndt succeed, can you help me ? and confused, should I use spread operator in this way , return from a function ?

newObject = {}

// use this inside a function and get value from return

       return {
         value: {
           ...newObject,
           ...initialState
         }
       }

initialState.isAvailable = true
question from:https://stackoverflow.com/questions/49491393/using-spread-operator-to-update-an-object-value

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The properties are added in order, so if you want to override existing properties, you need to put them at the end instead of at the beginning:

return {
  value: {
    ...initialState,
    ...newObject
  }
}

You don't need newObject (unless you already have it lying around), though:

return {
  value: {
    ...initialState,
    isAvailable: newValue
  }
}

Example:

const o1 = {a: "original a", b: "original b"};
// Doesn't work:
const o2 = {a: "updated a", ...o1};
console.log(o2);
// Works:
const o3 = {...o1, a: "updated a"};
console.log(o3);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.8k users

...