Javascript-如何破坏对象并克隆属性?

时间:2020-03-05 14:14:37

标签: javascript ecmascript-6 destructuring

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

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

2 个答案:

答案 0 :(得分:4)

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

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

答案 1 :(得分:0)

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

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

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