2017-09-13 49 views
-7

我有以下代碼:JavaScript的過濾器和片不能正常工作

conditions.slice(0).filter(condition => condition.processsteptemplate === stepId); 

應該切一些對象進行數組。問題是===不匹配,因此所有的元素仍然在數組中......

什麼我的失敗

UPDATE:

示例代碼:

var conditions = [{ 
 
     id: 14, 
 
     conditiontype: 1, 
 
     processsteptemplate: 9, 
 
     deleted: false, 
 
     processTemplate_id: 0 
 
    }, 
 
    { 
 
     id: 15, 
 
     conditiontype: 1, 
 
     processsteptemplate: 9, 
 
     deleted: false, 
 
     processTemplate_id: 0 
 
    }, 
 
    { 
 
     id: 16, 
 
     conditiontype: 1, 
 
     processsteptemplate: 10, 
 
     deleted: false, 
 
     processTemplate_id: 0 
 
    } 
 
    ], 
 
    stepId = 9; 
 
    
 
const output = conditions.slice(0).filter(condition => condition.processsteptemplate === stepId); 
 
console.log(output)

+4

爲什麼'conditions.slice(0).filter'? '過濾器'無論如何會返回另一個數組。 – Rajesh

+0

只是刪除切片? – Felix

+1

嘗試'var output = conditions.filter(x => x.processsTemplate === stepId);的console.log(輸出)'。要點是,'filter'永遠不會操縱你的原始數組。它會返回已過濾值的列​​表 – Rajesh

回答

2

這裏processsteptemplate = 10的陣列被刪除

let arr = [ 
 
{id: 14, conditiontype: 1, processsteptemplate: 9, deleted: false, processTemplate_id: 0}, 
 
{id: 15, conditiontype: 1, processsteptemplate: 9, deleted: false, processTemplate_id: 0}, 
 
{id: 16, conditiontype: 1, processsteptemplate: 10, deleted: false, processTemplate_id: 0} 
 
] 
 

 
let step = 9; 
 

 
let result = arr.filter((e) => e.processsteptemplate === step); 
 

 
console.log(result);

你可能做什麼錯了,你是假設

arr.filter((e) => e.processsteptemplate === step); 

將當前的數組中更改數值,這是不正確的,它會返回一個新的數組,現在存儲在結果,你現在可以看到在上面的代碼片段

+0

添加了問題的編輯 – marvel308

+0

說實話,我已經在評論中解決了這個問題。此外,如果您閱讀文檔,這樣的問題可以解決。所以回答他們,是在我的POV中,錯了。我仍然會進行投票,因爲它確實回答了問題。 – Rajesh