开发者问题收集

根据现有过滤创建一个新数组

2021-07-06
68

我正在编写一个代码,要求使用字符串过滤对象数组,并根据过滤后的值创建一个新数组。

这是我的代码。

var a = [{
  "label": "June - 2021",
  "value": "June"
}, {
  "label": "May - 2021",
  "value": "May"
}, {
  "label": "April - 2021",
  "value": "April"
}];
var b = ["June", "May"];
var healthTemp = [];
a.forEach(item => {
  var idx = b.value.indexOf(item);
  console.log(idx);
  if (idx == 0) healthTemp.add('Previous month')
  if (idx == 1) healthTemp.add('2 months ago')
  if (idx == 2) healthTemp.add('3 months ago')
});

由于 b 中有六月和五月,索引分别为 01 ,因此我希望 healthTemp['Previous month', '2 months ago'] 。但这会给我一个错误。请让我知道我哪里做错了,我该如何修复?

感谢 Chris 的建议,我已更新了我的问题,将 = 替换为 == 。现在我收到错误 Uncaught TypeError: Cannot read property 'indexOf' of undefined"

3个回答

我认为您想要做的是这样的:

var a = [{
    "label": "June - 2021",
    "value": "June"
  }, {
    "label": "May - 2021",
    "value": "May"
  }, {
    "label": "April - 2021",
    "value": "April"
  }];
  var b = ["June", "May"];
  var healthTemp = [];
  healthTemp
  b.forEach (month => {
      a.forEach((item,idx) => {
          if(item.value == month) {
            console.log(idx);
            if (idx == 0) healthTemp.push('Previous month')
            if (idx == 1) healthTemp.push('2 months ago')
            if (idx == 2) healthTemp.push('3 months ago')
          }
      })
  })
λambduh
2021-07-06

另一个版本:

const a = [{
  "label": "June - 2021",
  "value": "June"
}, {
  "label": "May - 2021",
  "value": "May"
}, {
  "label": "April - 2021",
  "value": "April"
}];

const b = ["June", "May"];



function foo(){
  const healthTemp = [];
  a.forEach(item => {
  const idx = b.indexOf(item.value);
    if(idx >=0){
      idx === 0 ? healthTemp.push('Previous month') : healthTemp.push(`${idx+1} months ago`)
    }
});
  return healthTemp
}

console.log(foo())
DoneDeal0
2021-07-06

如果我正确理解了您的问题,我将按如下方式解决它:

// Given a `mont` string, find the first item of `a` whose `value` property
// equals the `month` string
// If month matches the first item of `a`, return "Previous month";
// If month matches the second item of `a`, return "2 months ago";
// If month matches the third item of `a`, return "3 months ago";
// etc...
// If month doesn't match any item of `a`, return "Never"
function howLongAgo (month) {
    for (let i=0; i<a.length; i++) {
        if (a[i].value === month) {
            return i == 0 ? "Previous month" : `${i+1} months ago`;
        }
    }
    return "Never";
}

const healthTemp = b.map(howLongAgo);
Marcello Del Buono
2021-07-06