gpt4 book ai didi

javascript - 删除循环内的多个 JSON 对象

转载 作者:行者123 更新时间:2023-11-28 12:54:56 25 4
gpt4 key购买 nike

我正在尝试创建一个循环,根据是否有 <p> 从我的 JSON 数组中删除 JSON 对象。元素具有选定的类。

所以,我希望它的工作方式是在提交表单时检查是否有 <p>元素具有选定的类。如果选择了任何元素,我会使用它们的文本值循环遍历它们,以将它们从 JSON 数组中删除,然后我 console.log()数组。

我可以使用循环内的代码从数组中删除单个对象,但我似乎无法让它与我的循环一起工作。我怎样才能实现这个目标?

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>

最佳答案

尝试这样。在您的 .each 循环中尝试推送数据,在过滤器中您可以检查 .indexOf()。这会给你结果。

I moved .filter out of .each loop. because loop inside loop is a bad idea and it will consume time.

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
}
];
$('#form').on('submit', function(e){
e.preventDefault();

if( $('.postcodes p.selected').length ){
var data = [];
$('.postcodes p.selected').each(function(){
data.push($(this).text());
});
var data_filter = area_json.filter((element) => {
return (data.indexOf(element.Sector)<0)
});
}

console.log(data_filter);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<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>

关于javascript - 删除循环内的多个 JSON 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56596659/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com