gpt4 book ai didi

javascript - 如何从javascript中的数组元素中删除对象

转载 作者:行者123 更新时间:2023-11-30 07:21:00 25 4
gpt4 key购买 nike

我正在使用 Javascript。我有一组数据需要根据元素值删除对象。在这里我附上了我的代码。在我的代码中,我有月份元素。我需要在月份为 1 时删除对象。如何做到这一点?

var Data=[ 
{ "State": "PA", "DispenseMonth": "1/1/2017" },
{ "State": "MS", "DispenseMonth": "1/1/2017" },
{ "State": "CT", "DispenseMonth": "1/1/2017" },
{ "State": "TX", "DispenseMonth": "2/1/2017"},
{ "State": "DE", "DispenseMonth": "2/1/2017"},
{ "State": "TN", "DispenseMonth": "2/1/2017" },
{ "State": "FL", "DispenseMonth": "3/1/2017" },
{ "State": "SD", "DispenseMonth": "4/1/2017" },
{ "State": "GA", "DispenseMonth": "5/1/2017"},
{ "State": "SC", "DispenseMonth": "6/1/2017"},
{ "State": "IA", "DispenseMonth": "7/1/2017" },
{ "State": "RI", "DispenseMonth": "8/1/2017" },
{ "State": "ID", "DispenseMonth": "9/1/2017"}
]

Data.forEach(item => {
return item.Month = item.DispenseMonth.split('/')[0];
});
console.log(Data);

我试过的代码:

 for(i = 0; i < MainStateData.length; i++) {
var bjMonth = MainStateData[i].Month;
if (bjMonth == 1) {
delete MainStateData[bjMonth];
MainStateData.splice([i]);
delete MainStateData[i];
}
}

最佳答案

试试 Data.filter(obj => obj["DispenseMonth"].split('/')[0] !== '1')filter 方法循环遍历 Data 数组并在每个对象上调用函数 obj => obj["DispenseMonth"].split('/')[0] !== '1'。如果回调返回 true,它会将项目保留在数组中。

Data = Data.filter(obj => obj["DispenseMonth"].split('/')[0] !== '1') 将有效地从数组中删除对象.

关于javascript - 如何从javascript中的数组元素中删除对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44149449/

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