Hi I've an array of object which I'm looping
let DOArr: [] =[]
{
"selectedDC": {
"DC": [{
"id": "23293839",
"name": "Legal · L5",
"active": true,
"parentid": "23293827",
"level": 4
},
{
"id": "23293839",
"name": "Balance · L2",
"active": true,
"parentid": "23293807",
"level": 2
}
]
}
}
for (const tmpDataOwner of this.dataConceptDetailsObj['selectedDC']['DC']) {
this.DOArr.push(tmpDataOwner.id)
}
Now I've so already populated checkbox formcontrols which I've selected default value as false.
I want to make those checkbox formcontrol true/checked whose id
and name
matches the above
const formControls = this.dataOwnerList.map(
(control) => {
if(this.DOArr.includes(control.id)){
return new FormControl(true);
}
else{
return new FormControl(false);
}
}
);
Now I'm only checking for id but I also want to check for name basically need strong checking for both id
& name
First, I propose dropping the for
in favor of mapping dataConceptDetailsObj
directly into DOArr
since it's less work. Then instead of pushing the id
on its lonesome, return a property bag with id
and name
keys whose values correspond to the current item.
let dataConceptDetailsObj = {
"selectedDC": {
"DC": [{
"id": "23293839",
"name": "Legal · L5",
"active": true,
"parentid": "23293827",
"level": 4
}, {
"id": "23293839",
"name": "Balance · L2",
"active": true,
"parentid": "23293807",
"level": 2
}]
}
}
let DOArr = dataConceptDetailsObj['selectedDC']['DC']
.map((item) => {
return {
id: item.id,
name: item.name
}
})
And for the second part:
Use the find
method of the DOArr array instead of includes
. Thus allowing you to check both the id and name.
The find() method returns the first element in the provided array that satisfies the provided testing function. If no values satisfy the testing function, undefined is returned. -MDN
const formControls = this.dataOwnerList.map(
(control) => {
let item = this.DOArr.find(
(i) => i.id == control.id && i.name == control.name
);
return new FormControl((item !== undefined));
}
);