I have the following where I am setting values inside children where children is of type HTMLCollection
.
All these values being set could be null. If null, I wish to remove the child entirely.
But how could I check if a child has value?
Note: Looking to remove it in a loop cos those keys already exists like someToken
.
Thus a null check to stop from adding a value to it will not suffice.
I still need to remove the key/value (child) entirely via loop.
Essentially looking for what I would write inside the if check to see if a child in the HTMLCollection
has a value.
// this is coming from another file.
const myRef = React.useRef();
myRef.current.children['someToken'] = null;
myRef.current.children['some id'] = 'someId';
myRef.current.children['another data'] = 'anotherData';
[...myRef.current.children].forEach((child) => {
// I want to remove the child entirely if there is no value.
// for example above, the key someToken, the value is set as null
// so in this case I want to remove the child.
// what would I write in the if check here to check that?
// if (!child) will always be false since key exists
if (!child) {
myRef.current.removeChild(child);
}
});
I would go for Object.entries
:
for (const [key, value] of Object.entries(myRef.current.children)) {
if (value === null)
myRef.current.removeChild(child);
}