I am trying to create a loop that removes JSON objects from my JSON array based on whether any <p> elements have the selected class.
So, how I want it to work is when the form is submitted I check to see if any <p> elements have the selected class. If any of the elements are selected I loop through them using their text value to remove them from the JSON array, then I console.log() the array.
I am able to remove a single object from the array using the code inside the loop but I can't seem to get it to work with my loop. How can I achieve this?
JS
$('#form').on('submit', function(e){
e.preventDefault();
if( $('.postcodes p.selected').length ){
$('.postcodes p.selected').each(function(){
var data_filter = area_json.filter((element) => {
return element.Sector !== $(this).text();
});
});
}
console.log(data_filter);
});
var area_json = [
{
"Sector": "AB10 1",
"Locality": "Thistle Court,Aberdeen",
"Residential": 1147
},
{
"Sector": "AB10 6",
"Locality": "Great Western Road,Aberdeen",
"Residential": 4596
},
{
"Sector": "AB10 7",
"Locality": "Holburn Street,Aberdeen",
"Residential": 4380
}
]
HTML
<form id="form" action="" method="post">
<div class="postcodes">
<p class="selected">AB10 1</p>
<p class="selected">AB10 6</p>
</div>
<input type="submit" value="submit">
</form>