【问题标题】:Using Javascript Array filter get all the matched classes from the array使用 Javascript 数组过滤器从数组中获取所有匹配的类
【发布时间】:2017-09-15 12:17:54
【问题描述】:

我想使用 filter 或任何 ES6 函数从 coachId === 2classes 数组中检索所有对象。

示例输入:

let arr = 
[
 {
  name: "boo",
  schedule: {
    classes: [ {coachId: 1}, {coachId: 2}, {coachId: 3}]
  }
 },
 {
  name: "foo",
  schedule: {
    classes : [ {coachId: 1}, {coachId: 2}, {coachId: 4}]
  }
 }
]

预期输出:

[ 
  [ {coachId: 2}], 
  [ {coachId: 2}] 
]

【问题讨论】:

  • 好的,我们现在有一些代码。但是预期的输出是什么? I want all the classes 是什么意思?你想要一个类数组吗?连接所有类?
  • 我想要@Jeremy Thille 的类数组
  • 所以你想要[ [{coachId: 1},{coachId: 2}, {coachId: 3}], [{coachId: 1},{coachId: 2}, {coachId: 3}] ]?数组数组?那是期望的输出吗? I want array of classes 还不清楚。 明确地编写所需的输出结构。
  • 我想要像 [ [ { coachId: 2}], [ {coachId: 2}] ] 这样的输出。 @杰里米蒂勒
  • 所以!现在你在说 :) 这只是使当前的两个答案无效。

标签: javascript ecmascript-6


【解决方案1】:

这就是你要找的吗?

const arr = 
[
 {
  name: "boo",
  schedule: {
    classes: [ {coachId: 1}, {coachId: 2}, {coachId: 3}]
  }
 },
 {
  name: "bar",
  schedule: {
    classes : [ {coachId: 1}, {coachId: 4}]
  }
 }, 
 {
  name: "foo",
  schedule: {
    classes : [ {coachId: 1}, {coachId: 2}, {coachId: 4}]
  }
 }
]

console.log(arr.reduce((result, item) => {
  result = [...result, ...item.schedule.classes.filter(classItem => classItem.coachId === 2)];
  return result;
}, []));

【讨论】:

  • 我只想要从 classes 数组中匹配的具有 coachId 为 2 的对象。你的代码是错误的。
  • 他的代码是错误的,因为你无法告诉完全使用所需的输出结构。我们只有I want array of classes
  • 现在看上面的OP评论:我想要像[ [ { coachId: 2}], [ {coachId: 2}] ]这样的输出
  • 更新了我的答案。结果略有不同,类没有包装在额外的数组中。
【解决方案2】:

var arr = 
[
 {
  name: "boo",
  schedule: {
	classes: [ {coachId: 1}, {coachId: 2}, {coachId: 3}]
  }
 },
 {
  name: "foo",
  schedule: {
	classes : [ {coachId: 1}, {coachId: 2}, {coachId: 4}]
  }
 }
];

var employeeId = 2;
var finalArr = arr.map(item => { 
	item.schedule.classes = item.schedule.classes.map(cls => { 
        cls.coachId = employeeId; 
        return cls; 
    });
    return item;
});
console.log(finalArr);

编辑:

var employeeId = 2;
var finalArr = [];
arr.forEach(item => { 
    var classes = item.schedule.classes.map(cls => { 
        cls.coachId = employeeId; 
        return cls; 
    });
    finalArr = finalArr.concat(classes);
});
console.log(finalArr);

【讨论】:

  • "Uncaught SyntaxError: Unexpected token =>"
  • 它有效,但我们仍然不知道 OP 想要什么。我们只知道他们想要array of classes
  • 现在看上面的OP评论:我想要像[ [ { coachId: 2}], [ {coachId: 2}] ]这样的输出
猜你喜欢
  • 1970-01-01
  • 2023-03-23
  • 2019-09-30
  • 1970-01-01
  • 2016-05-28
  • 1970-01-01
  • 2021-08-22
  • 1970-01-01
  • 2021-12-03
相关资源
最近更新 更多