【问题标题】:Javascript map within filter过滤器内的 Javascript 映射
【发布时间】:2019-01-30 19:19:45
【问题描述】:

我正在尝试向我的单位数组添加一个属性(分数)。 Scores 是一个对象数组,其中包含一个带有单位的公共 id。

 this.units.map(unit => {
              unit.score = scores
              .filter(score => unit.id === score.unit_id);
 });

数组中包含的对象。

 scores
    {
      unit_id: 1234,
      score: 12,
    }


 this.units
  [
    {
      id: 1234,
      type: 'maths',

    }
   {
      id: '5678',
      type: 'maths',

    }
  ]

看起来不错。是不是因为unit.id在过滤器中不可用?

【问题讨论】:

  • 现在您已经编辑了问题中的代码,所以它可以工作了,那么问题是什么?

标签: javascript arrays filter mapping


【解决方案1】:

我想这就是你所追求的。 score没有unit_id属性,只有id。

var scores = [{
  unit_id: 1234,
  score: 12,
}];
var units = [{
  id: 1234,
  type: 'maths',
}, {
  id: 5678,
  type: 'maths',
}];

units.map(unit => {
  unit.score = scores
    .filter(score => unit.id === score.unit_id);
});

console.log(units);

【讨论】:

  • 谢谢,我快到了,我想我只是绕了一圈。
  • 您不应该为此使用.map,因为它不会返回任何值。请改用.forEach
猜你喜欢
  • 2014-07-23
  • 2019-05-19
  • 1970-01-01
  • 2020-11-23
  • 1970-01-01
  • 1970-01-01
  • 2020-06-27
  • 2011-05-11
  • 2011-04-10
相关资源
最近更新 更多