Parkicism Parkicism - 5 months ago 14
JSON Question

How do I make an undefined item in an object's length equal to 0 in reactjs?

I am trying to keep track of the scores in each article and display it. However, I run into problems when it's missing an up or down item in the object.

This is my data for all the votes:

const votes = {
"1": {
"up": [
"12345",
"12346"
],
"down": [
"22456"
],
},
"2": {
"up": [
"12345",
"12346"
],
"down": [
"22456",
"25214",
"23612"
]
}
}

export default votes;


This is how I'm handling it right now, but this requires that there has to be both
"up"
and
"down"
in the object.

<div style={vote}>
{votes[id] ? votes[id].up.length - votes[id].down.length : 0 }
</div>


So in a case here you have only the
up
element, I want the result to be only the length of up. And the same case for down:

"3": {
"up": [
"12345",
"22341"
]
} //this would output a score of 2


Any help would be greatly appreciated, Thanks!

Answer

The preferrable solution would probably be to always initialize the objects with a blank up and down array when you add it to your votes array.

If that's not possible, you will have to handle this case during the rendering process, e.g. like this:

<div style={vote}>
    {votes[id] ? (votes[id].up || []).length - (votes[id].down || []).length : 0 }
</div>
Comments