具有多个条件的过滤器阵列

时间:2019-07-27 19:50:50

标签: javascript arrays

我有一个对象数组,我想在多个条件下对其进行过滤。 element.state === falseelement.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
 * }
 */

有人建议我在做什么错吗?

感谢您的答复!

2 个答案:

答案 0 :(得分:3)

几个问题:

  1. return中没有filter()

  2. URL以/结尾,因此不等于para的字符串也没有以/结尾的字符串

  3. 您的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>

答案 1 :(得分:2)

您要设置para = 'category',但网址为'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