【问题标题】:Javascript - How to destruct an object and clone a property?Javascript - 如何破坏对象并克隆属性?
【发布时间】:2020-03-05 14:14:37
【问题描述】:

我想在一行中破坏一个对象并克隆一个特定属性。有可能吗?

const MyObject = {
  sections: [1, 2],
  otherProp: null
};

const { sections } = MyObject; // Not a copy/clone of the array
const sectionsClone = { ...MyObject.sections }; // Works - But is not a destructuration

// Ideal scenario (I know this syntax has an error)
const { ...sections: myIdealScenario } = MyObject

【问题讨论】:

  • const { sections } = MyObject; 之后,为什么不理想?
  • 这叫“去结构”和“去结构”
  • 如果您想复制数组,请明确说明:const sections = MyObject.sections.slice()

标签: javascript ecmascript-6 destructuring


【解决方案1】:
const MyObject = {
  sections: [1, 2],
  otherProp: null
}

const { sections: [...sections] } = MyObject

【讨论】:

  • 就是这样!在我的示例中,我只包含一个道具;但是,是的,通过这个解决方案,我可以在一行中包含多个道具。太棒了!
【解决方案2】:

我认为你只是想克隆对象中的数组,你不需要解构它:

const MyObject = {
  sections: [1, 2],
  otherProp: null
};

const myIdealScenario = [...MyObject.sections];

【讨论】:

    猜你喜欢
    • 2015-02-08
    • 1970-01-01
    • 2013-05-21
    • 2016-08-05
    • 1970-01-01
    • 2018-08-08
    • 2017-05-22
    • 2013-01-03
    • 1970-01-01
    相关资源
    最近更新 更多