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

时间:2018-12-27 01:22:54

标签: javascript jquery json

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

我需要能够根据用户选择的内容来过滤并获取类别中所有活动的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
        },
      ]
    },
  ]
};

2 个答案:

答案 0 :(得分:3)

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'))

答案 1 :(得分:1)

这里是一个版本,主要使用数组的reduce()方法仅获取某个类别的var btnHCon: Constraint? = nil expandButton.snp.makeConstraints { (make) in make.top.equalTo(titleLabel.snp.bottom).offset(10) make.left.equalTo(10) make.right.equalTo(-15) make.bottom.equalTo(-15) self.btnHCon = make.height.equalTo(40).constraint } 列表。如果您希望所有包装这些活动名称的对象,都可以简化。

activityNames