我有一个对象数组,我想在多个条件下过滤它们。如果 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
url 以
/
结尾,因此不会等于para
字符串也未以/
/结尾p>您的
<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>
关于javascript - 具有多个条件的过滤器数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57235567/