I just want to copy value from "all" to "available" and I can't get value from available sometimes all too.
I have try many ways such as slice(), Array.from() and = but it's not work
let a = [{"key":66,"value":"MAAA","username":"MAZA007"},{"key":66,"value":"MAAA","username":"MAZA007"}];
let all = a
let available = all
Just no value in my variable
This is my full function
protected async processMoverBox(projectId?:number) {
let available;
let all;
if(projectId != undefined)
{
let projectTeamId = await this.restful.get("api/operation/S200100/allprojectteam/"+projectId);
console.log(projectTeamId)
all = projectTeamId.map((id) => {return this.copy(this.allUser.find(allUser => allUser.key == id))})
}
else{ all = this.copy(this.allUser); console.log(this.allUser)}
console.log(all);
let a = [{"key":66,"value":"MAAA","username":"MAZA007"},{"key":66,"value":"MAAA","username":"MAZA007"}]
available = [...a];
console.log(available);
console.log(JSON.stringify(available, null, 4));
if(this.selected.length>0){
this.selected.forEach((ms)=>{
available.splice(available.findIndex(e => e.key == ms.key), 1);
})
}
console.log(available);
console.log(this.selected)
this.memberDualbox.initMoveBox(available, this.selected, all)
this.memberDualbox.disabled = this.isViewMode;
}
You can assign value like the bellow example.
let a = [{"key":66,"value":"MAAA","username":"MAZA007"},{"key":66,"value":"MAAA","username":"MAZA007"}];
let all = a
let available = Object.assign({}, all);
Your code is working.
However, your code isn't "copying" the data from the array assigned to variable "a". What you are doing is creating additional variables "all" and "available" that all point to the same array in memory via reference value. An array is a reference value type. If you want to create a brand new copy/clone of the array then there are various techniques. As per @uminder above you can create a shallow copy using slice.
let available = all.slice(0);
Or you could use spread syntax:
let available = [...all];
Full example:
(function() {
const a = [{
"key": 66,
"value": "MAAA",
"username": "MAZA007"
}, {
"key": 66,
"value": "MAAA",
"username": "MAZA007"
}];
const all = a;
//Returns true (same reference)
console.log(all === a);
const available = [...all];
//Returns false (new reference)
console.log(available === a);
//Alterntive syntax example shallow copy
//let available = all.slice(0);
console.log(JSON.stringify(available, null, 4));
}
)();
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