gpt4 book ai didi

javascript - 如何使用 JQuery 过滤 JSON 对象并创建新对象?

转载 作者:行者123 更新时间:2023-12-01 03:06:53 26 4
gpt4 key购买 nike

我有一个 JSON 数据库,需要对其进行过滤,然后能够仅显示所选元素(按 Category)的参数(ActivityName) )。

我需要能够根据用户选择的内容过滤并获取类别内所有事件的ActivitiesNames

我正在尝试通过执行以下操作来创建一个具有此过滤版本的数据库的对象:

var selectedCategory = $(activitiesDatabase.Categories).filter(function(i, n)
{
return n.CategoryID === selectedCategory;
});

但它显然不起作用。有什么想法可以解决这个问题吗?

谢谢! (以下是 JSON 数据库的示例)

var activitiesDatabase = 
{
"Categories": [
{
"CategoryId": "cashFlow",
"Activities": [
{
"ActivityName": "Measure and analyse cash flows" ,
"EstimatedTime": 20
},
{
"ActivityName": "Measure and analyse cash flows" ,
"EstimatedTime": 20
},
]
},
{
"CategoryId": "growthStrategies",
"Activities": [
{
"ActivityName": "Research market and identify trends" ,
"EstimatedTime": 30
},
{
"ActivityName": "Research market and identify trends" ,
"EstimatedTime": 30
},
]
},
]
};

最佳答案

jQuery 的过滤器设计用于处理一组匹配的 DOM 元素

您不需要 jQuery,Array.prototype.filter 即可完成此工作:

var activitiesDatabase = { "Categories": [ { "CategoryId": "cashFlow", "Activities": [ { "ActivityName": "Measure and analyse cash flows" , "EstimatedTime": 20 }, { "ActivityName": "Measure and analyse cash flows" , "EstimatedTime": 20 }, ] }, { "CategoryId": "growthStrategies", "Activities": [ { "ActivityName": "Research market and identify trends" , "EstimatedTime": 30 }, { "ActivityName": "Research market and identify trends" , "EstimatedTime": 30 }, ] }, ] };

const activitiesByCategoryId = categoryId => activitiesDatabase.Categories.filter(({ CategoryId }) => CategoryId === categoryId)

console.log(activitiesByCategoryId('cashFlow'))

关于javascript - 如何使用 JQuery 过滤 JSON 对象并创建新对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53938798/

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