In my project I am moving from XML format to JSON format.
I have XML which consists from nodes like this:
<Creature>
<Name>Someone</Name>
<Desert>false</Desert>
<Woods>false</Woods>
<Mountains>false</Mountains>
<Swamp>false</Swamp>
</Creature>
And the radio list with values equal to the tags names. Like this:
<input type="radio" name="creature_terrain" value="Desert" />Desert<br>
Old code filtered XML list by doing this:
let selector = 'Creature > ' + selectedTerrain + ':contains("true")';
var filteredCreatures = $(creaturesArray).find(selector).parent();
And so now I have JSON array:
{
"Name": "Someone",
"Desert": false,
"Woods": false,
"Mountains": false,
"Swamp": false
}
But I can’t find a way to filter it as elegant as it was with XML. The only way I see is to switch/case. Any suggestions?
3
Answers
If it actually is an array, you can use
filter
to go through looking for the matching terrain is true.EDIT: You could leave out the == true as it will evaluate it as boolean, but I prefer having it as its easier to read and understand.
Try javascript native array methods like find or filter.
Assuming you have an array of objects rather than just one object you can use
filter
to filter out those object that match a specific condition.Let’s expand your example.
There are two objects (I’ve lowercased the key names). One matches "desert" the other "swamp". There are corresponding radio inputs for demonstration.
I’ve attached an event listener to the
fieldset
element to catch events from its children (event delegation).When a change event is fired the handler checks first to see if the element that fired the event was an radio button. Then it
filters
out the objects into a new array that match the "is the value of this object key true?" condition. We use thevalue
of the changed radio button as the object key that we want to inspect.For convenience this filtered array of objects is displayed in an output element.