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

标签 javascript html underscore.js

我有一个对象数组如下:

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

我想根据 productionLine 值根据 ex 的 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);

关于javascript - 如何使用下划线javascript过滤数组数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58702554/

相关文章:

javascript - 带有 Express 的 Node.js - 返回指向 .CSV 文件的链接而不是下载它

javascript - SVG 尺寸在悬停时永久改变

javascript - 使用 JS 时字体很棒的图标和面板无法正确显示

Javascript - 检查文本/模板脚本中是否存在字段

javascript - 没有 cookie 的 XMLHttpRequest

javascript - 有什么理由使用 !0 而不是 true 吗?

javascript - 需要帮助使用 jquery 计时事件

javascript - 从 html.append 附加的 html 下拉列表中获取返回值

javascript - 迭代对象属性并修改它们

javascript - 嵌套依赖性 Backbone.js View 与 Require.js Backbone.js 导致 View 加载为对象而不是函数