如何使用下划线 javascript 过滤数组数组

how to filter an array of array using underscore javascript

我有一个对象数组如下:

[{name:'Initiative 1', actionList:[{name:'action 1', productionLine:'436767'}]}, {name:'Initiative 2', actionList:[{name:'action 2', productionLine:'892128'}]}]

而且我想根据 productionLine 值根据某些 属性 的 actionList 元素过滤结果。

这是我的代码,没有按预期工作,我得到一个空结果。

initiatives.forEach(function(initiative) {
     var newArr = _.filter(initiative.actionList, function({
         return o.productionLine == selectedProductionLine;
     });
     initiative.actionList = newArr;
});

预计: 输入给定:892128 结果:

[{name:'Initiative 1', actionList:[]}, {name:'Initiative 2', actionList:[{name:'action 2', productionLine:'892128'}]}]

语法与您的过滤器不符:

var newArray = arr.filter(callback(element[, index[, array]])[, thisArg])

查看Array.prototype.filter()

下面的代码片段应该能满足您的需求。

let initiatives = [{
  name: 'Initiative 1',
  actionList: [{
    name: 'action 1',
    productionLine: '436767'
  }]
}, {
  name: 'Initiative 2',
  actionList: [{
    name: 'action 2',
    productionLine: '892128'
  }]
}]

let selectedProductionLine = '892128';

initiatives.forEach(function(initiative) {
  newArray = initiative.actionList.filter(function(actionList) {
    return actionList.productionLine == selectedProductionLine;
  });
  initiative.actionList = newArray
});

console.log(initiatives);