簡體   English   中英

如何使用下划線 javascript 過濾數組數組

[英]how to filter an array of array using underscore javascript

我有一個 object 數組,如下所示:

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

我想根據 actionList 元素的某些屬性過濾結果,例如基於 productionLine 值。

這是我的代碼,它沒有按預期工作,我得到一個空結果。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM