我想使用status
密钥将所有任务列表数据过滤为打开和已关闭任务列表
var data = [{
"createdOn": "Created on Jan 07, 2017",
"taskList": [{
"task": "Meeting with Jason",
"status": "closed",
},
{
"task": "Meeting with Ram",
"status": "open",
},
]
},
{
"createdOn": "Created on Jan 08, 2017",
"taskList": [{
"task": "Meeting with Mike",
"status": "open",
},
{
"task": "Meeting with Smith",
"status": "closed",
},
]
}
];
我试过这个:
console.log(_.filter(data, { taskList: [ { status: "open" } ]}));
实际结果:
根据数据,TaskList数组在1月7日和1月08日包含2个开放状态。但是我得到了一个完整的taskList数组。
0:{createdOn: "Created on Jan 07, 2017", taskList: Array(2)}
1:{createdOn: "Created on Jan 08, 2017", taskList: Array(2)}
预期结果:
0:{createdOn: "Created on Jan 07, 2017", taskList: "taskList": [{
"task": "Meeting with Ram",
"status": "open",
}}
1:{createdOn: "Created on Jan 08, 2017", taskList: "taskList": [{
"task": "Meeting with Mike",
"status": "open",
}}
答案 0 :(得分:1)
您的filter
错了。
var data = [{
"createdOn": "Created on Jan 07, 2017",
"taskList": [{
"task": "Meeting with Jason",
"status": "closed",
},
{
"task": "Meeting with Ram",
"status": "open",
},
]
},
{
"createdOn": "Created on Jan 08, 2017",
"taskList": [{
"task": "Meeting with Mike",
"status": "open",
},
{
"task": "Meeting with Smith",
"status": "closed",
},
]
}
];
var newArray = data.filter(function (el) {
el.taskList = el.taskList.filter(function(item)
{
return item.status == "open";
});
return el;
});
console.log(newArray);

答案 1 :(得分:0)
如果您想要包含status='open'
的过滤条件,那么您的过滤器就可以了。如果要返回修改过的对象,那就是另一个故事。这是ECMAS6 lodash / vanilla:
// lodash
console.log(_.map(data, o => o.taskList = _.filter(o.taskList, { 'status': 'open' })));
// vanilla
console.log(data.map(o => o.taskList = o.taskList.filter(t => t.status == 'open')))
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
<script>
var data = [{
"createdOn": "Created on Jan 07, 2017",
"taskList": [{
"task": "Meeting with Jason",
"status": "closed",
},
{
"task": "Meeting with Ram",
"status": "open",
},
]
},
{
"createdOn": "Created on Jan 08, 2017",
"taskList": [{
"task": "Meeting with Mike",
"status": "open",
},
{
"task": "Meeting with Smith",
"status": "closed",
},
]
}
];
</script>