private copyTableByStatus(table: Table, status: string): Table{
// XXX: Weird, javascript can't deep copy. Object.assign() only creates
// shallow copies. There should be something like Object.clone() ...
let newTable: Table = JSON.parse(JSON.stringify(table));
newTable.checkins = newtable.checkins.map(
checkin => {
checkin.items = checkin.items.filter(
item => item.statusOItem == status
)
return checkin;
}
)
return newTable;
}
This shows the shortcomings of java that there is no way to deep copy stuff. Object.assign only shallow copies and this workaround doesn’t copy function of the object!
EDIT: Edited code to be shorter and more perfomant.
Dont embed JSON.parse like that, it isn’t performant. If you need a deep copy (which you didn’t say in your question) inside a loop, you might need to write one. But this is probably a weakness in logic. You could give each item a unique ID, and then just do operations on arrays of strings, where each element of the array is an ID. Then you map from strings to the full object whenever you need to.
Hmm apart from me not understanding your answer (sorry english is not my native language), I feel like doing this a couple of times won’t affect performance that much.
You have a master array of all things. Create a string array of all ids. You create a list of all visible things by filtering the array of ids. You then display a thing by using a Map<string, thing>.
As far as I’ concerned the spear operator only copies shallow, doesn’t it? And you are circumventing this by putting the spear in front of checkin AND table, if I understand correctly?
if table or checkin have any properties that refer to any other objects, these objects don’t get copied. You have to copy them manually. But primitive properties (string, boolean, number, etc) get copied.
Spread operator is a little bit like Object.assign. Doing shallow copies.
You could use something like this, but i don’t know, if it is better then JSON.stringify(JSON.parse(obj)) regarding performance. It is an example I just wrote for you, so it is not production ready. But there should be libraries that do similar things.
function deepcopy(obj: any) {
if (Array.isArray(obj)) {
return obj.map(item => deepcopy(item));
}
if (obj === null) {
return obj;
}
if (typeof obj === 'object') {
return Object.keys(obj).reduce((acc, curr) => ({ ...acc, [curr]: deepcopy(obj[curr]) }), {})
}
return obj;
}
It supports all kind of features and can also clone complex structures. But it is slower compared to JSON.
The library owner describes it here:
You can install lodash to your project with: npm i -S lodash npm i -D @types/lodash
There is also a smaller version npm i -S lodash.clonedeep
But i don’t know if the types are working for it.
It really depends on what you are doing. If you know exactly the data structure and it is not that big, I would use the spread operator for cloning, if performance is very important.