I have a javascript object that represents form fields. about 70% of these fields have to be copied in some objects for sending to server, other fields are for UI usage. Presently I clone objects by manually creating assignments for each field, that result in rather not nice structures, as shown below. Note that I would keep field names identical for parts being copied.
var contData = {
ContainerType: data.ContainerType,
ProjectIds: data.ProjectIds,
PrivateToProjects: data.PrivateToProjects,
DimensionType:data.DimensionType,
MetricsX: data.MetricsX,
MetricsY: data.MetricsY,
Parent:data.Parent,
ContainerName:data.Prefix
};
What would be the best way to code cloning part of object, just specifying list of fields to clone/not to clone, such as some useful helper function?
I also use angular and jquery.
After ES6, you could
let { ContainerType, ProjectIds } = data // the fields you want
let partiallyCopy = { ContainerType, ProjectIds }
console.log(partiallyCopy) // { ContainerType: "...", ProjectIds: "..." }
And if you need most fields, you could
let { ContainerType, ProjectIds, ...rest } = data // the fields you don't want
let partiallyCopy = rest
console.log(partiallyCopy) // the object excludes ContainerType and ProjectIds
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With