使用价差运算符更新对象值 [英] Using spread operator to update an object value

查看:59
本文介绍了使用价差运算符更新对象值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个向传入对象添加键的函数,但是有人告诉我使用扩展运算符,有人告诉我可以使用扩展运算符创建具有相同属性的新对象,然后进行设置isAvailable就可以了.

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 = {}

newObject = {}

///在函数中使用它并从return中获取值

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

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

initialState.isAvailable = true

initialState.isAvailable = true

推荐答案

按顺序添加属性 ,因此,如果要覆盖现有属性,则需要将其放在末尾而不是一开始:

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
  }
}

不过,您不需要newObject(除非您已经将它放在身边)

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

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

示例:

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);

这篇关于使用价差运算符更新对象值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆