我想破坏对象并克隆特定属性,所有这些都在一行中。有可能吗?
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
您不能同时破坏和克隆。相反,您可以简单地使用spread syntax从MyObject.sections
中的所有元素创建一个新数组:
const sections = [...MyObject.sections]
说过...
这是可怕的代码(它声明了一个临时变量sections
,并使用comma operator),但您要求涉及分解的单线代码,因此,您可以进行以下操作:
const MyObject = {
sections: [1, 2],
otherProp: null
};
const clonedSections = (({ sections } = MyObject), [...sections])
console.log(clonedSections)
console.log(clonedSections === MyObject.sections)
我想您只是想在对象中克隆数组,不需要解构它:
const MyObject = {
sections: [1, 2],
otherProp: null
};
const myIdealScenario = [...MyObject.sections];
const MyObject = {
sections: [1, 2],
otherProp: null
}
const { sections: [...sections] } = MyObject