gpt4 book ai didi

javascript - 如何通过特定键过滤javascript中的对象

转载 作者:行者123 更新时间:2023-11-28 13:01:15 25 4
gpt4 key购买 nike

我在数组[0]中有以下对象:

   [
{
"startDay": "05-06",
"endDay": "05-06",
"startTime": "xxxx",
"eventType": "craft"
},
{
"startDay": "05-05",
"endDay": "05-06",
"startTime": "1400",
"eventType": "art"
},
{
"startDay": "05-08","endDay": "05-08",
"startTime": "1100",
"eventType": "music"
},
{
"startDay": "05-08","endDay": "05-08",
"startTime": "1400",
"eventType": "fishing"
},
{
"startDay": "05-07","endDay": "05-08",
"startTime": "1400",
"eventType": "football"
}
]

如何按 item.startDay 过滤此内容?例如如果过滤器为“05-06”,则过滤后的结果为:

[{
"startDay": "05-06",
"endDay": "05-06",
"startTime": "xxxx",
"eventType": "craft"
}]

如果过滤器为“05-08”,则过滤后的结果为:

[{
"startDay": "05-08","endDay": "05-08",
"startTime": "1100",
"eventType": "music"
},
{
"startDay": "05-08","endDay": "05-08",
"startTime": "1400",
"eventType": "fishing"
}]

最佳答案

您可以使用filter方法并传递回调提供的函数作为参数。

The filter() method creates a new array with all elements that pass the test implemented by the provided function.

let data = [ { "startDay": "05-06", "endDay": "05-06", "startTime": "xxxx", "eventType": "craft" }, { "startDay": "05-05", "endDay": "05-06", "startTime": "1400", "eventType": "art" }, { "startDay": "05-08","endDay": "05-08", "startTime": "1100", "eventType": "music" }, { "startDay": "05-08","endDay": "05-08", "startTime": "1400", "eventType": "fishing" }, { "startDay": "05-07","endDay": "05-08", "startTime": "1400", "eventType": "football" } ]

let startDay = "05-08";
data = data.filter(function(item){
return item.startDay == startDay;
});
console.log(data);

另一种方法是使用箭头函数。

let data = [ { "startDay": "05-06", "endDay": "05-06", "startTime": "xxxx", "eventType": "craft" }, { "startDay": "05-05", "endDay": "05-06", "startTime": "1400", "eventType": "art" }, { "startDay": "05-08","endDay": "05-08", "startTime": "1100", "eventType": "music" }, { "startDay": "05-08","endDay": "05-08", "startTime": "1400", "eventType": "fishing" }, { "startDay": "05-07","endDay": "05-08", "startTime": "1400", "eventType": "football" } ]

let startDayParam = "05-08";
data = data.filter(({startDay}) => startDay == startDayParam);
console.log(data);

关于javascript - 如何通过特定键过滤javascript中的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50221873/

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