简体   繁体   中英

Javascript - How to destruct an object and clone a property?

I want to destruct an object and clone a specific property, all in a single line. It's possible?

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 MyObject = {
  sections: [1, 2],
  otherProp: null
}

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

I think you're just trying to clone the array in the object, you don't need to destructure it:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM