如何用子对象过滤对象

时间:2018-10-18 14:58:46

标签: javascript jquery ecmascript-6

我有一个使用AJAX检索的对象。 AJAX将返回一个具有无限节点的对象,并且每个节点可以有自己的子节点。我想用Title过滤此对象,所以我只能得到标题项目。

我的想法是,如果响应中有任何title: 'project',我会做一件事,否则我会做另一件事。

如何使用下面的代码片段获取此多级对象并对其进行过滤?我尝试了filter,但是没有用。我试图使grep工作,但是我做错了,因为它也行不通。我愿意接受ES5 / ES6和TS解决方案。

$.mockjax({
  url: '/node/initdata',
  responseTime: 100,
  contentType: 'application/json',
  responseText: {
    "id": "33",
    "collapsed": false,
    "name": "Plan",
    "title": "BusinessPlan",
    "children": [{
      "id": "266",
      "collapsed": false,
      "name": "addd",
      "title": "BusinessPlanObjGoal",
      "children": [{
        "id": "65",
        "collapsed": false,
        "name": "Adding information ",
        "title": "Kpi",
        "children": [],
        "due": 7
      }, {
        "id": "99",
        "collapsed": false,
        "name": "addd",
        "title": "Project",
        "children": []
      }]
    }, {
      "id": "267",
      "collapsed": false,
      "name": "adddasdas",
      "title": "BusinessPlanObjGoal",
      "children": [{
        "id": "55",
        "collapsed": false,
        "name": "Adding new item",
        "title": "Kpi",
        "children": [],
      }]
    }, {
      "id": "268",
      "collapsed": false,
      "name": "plan 2",
      "title": "BusinessPlanObjGoal",
      "children": [{
        "id": "299",
        "collapsed": false,
        "name": "Teste Gui",
        "title": "BusinessPlanObjGoal",
        "children": []
      }]
    }]
  }
});

$.ajax({
  url: '/node/initdata',
  type: 'GET',
  dataType: 'json',
  statusCode: {
    400: function() {
      alert('Wrong Format!!!');
    }
  },
  complete: function(data, status) {
    jsonData = data.responseJSON;
    console.log(jsonData);
    /* 
    dt = cdt.filter(function (entry){
      return entry.title==='department manager';
    });
    console.log(dt);
    */
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-mockjax/1.6.2/jquery.mockjax.min.js"></script>

0 个答案:

没有答案