[英]Filter array with multiple conditions
我有一個對象數組,我想在多個條件下過濾它們。 如果element.state === false
或者element.url
包含某個或多個字符串。
我嘗試使用某個字符串進行過濾,但是返回了一個空數組。 在我的示例下面找到:
const attr = ['Product 1', 'Product 2'] const res = [] for (let i = 0; i < attr.length; i++) { res.push({ attr: attr[i], url: 'category/', state: false, }, { attr: attr[i], url: 'costs/', state: false, }, { attr: attr[i], url: 'ownership/', state: false, }, { attr: attr[i], url: 'earnings/', state: false, }, { attr: attr[i], url: 'price/', state: false, }) } /* console.log(JSON.stringify(res)) */ function setState(obj, bool) { obj.state = bool } function getState(res) { return res.state } setState(res[1], true) const para = 'category' let currentState = res.filter((el, para) => { el.state === false && el.url === para }) console.log(`Initial state: ${currentState.length}`) while (currentState.length > 0) { currentState[0].state = true currentState = res.filter(el => el.state === false) console.log(`Set state to true for ${JSON.stringify(currentState[0])}`) console.log(currentState.length) } console.log('###################DONE#####################') /* * ################ * #Wanted Output for 'category' and 'ownership' * ################ * { * attr: 'Product 1', * url: 'category/', * state: true * }, * { * attr: 'Product 2', * url: 'category/', * state: true * }, * { * attr: 'Product 1', * url: 'ownership/', * state: true * }, * { * attr: 'Product 2', * url: 'ownership/', * state: true * } */
有什么建議我做錯了嗎?
感謝您的答復!
幾個問題:
filter()
不return
網址以/
結尾,因此不會等於也不以/
結尾的para
字符串
您的filter()
使用的參數名稱為para
也將para
變量隱藏在其外部
const para = 'category' let currentState = res.filter((el) => { return el.state === false && el.url.startsWith(para) }) console.log(currentState)
<script> const attr = ['Product 1', 'Product 2'] const res = [] for (let i = 0; i < attr.length; i++) { res.push({ attr: attr[i], url: 'category/', state: false, }, { attr: attr[i], url: 'costs/', state: false, }, { attr: attr[i], url: 'ownership/', state: false, }, { attr: attr[i], url: 'earnings/', state: false, }, { attr: attr[i], url: 'price/', state: false, }) } </script>
您正在設置para = 'category'
但是url為'category/'
因此過濾不返回任何內容。
另外,在函數中:
let currentState = res.filter((el) => { // <- removed the second element "para" because it will hold the index of el in res, which is not what you intended.
el.state === false && el.url.indexOf(para) > -1; // check if it's a substring
})
para
的名稱具有誤導性:第二個參數是元素的索引,它“隱藏”了您在外部聲明的常量para
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.