如何过滤此数组中大于或等于90的标记?

时间:2018-11-02 13:40:52

标签: javascript arrays node.js arraylist filter

let students = [
  {"Name": "Priya","marks": [50, 60, 70, 80, 90]},
  {"Name": "Ankita","marks": [80, 90, 95]}
] 

结果应该是这样

[{"Name": "Priya", "marks": [90]}, {"Name": "Ankita","marks": [90,95]}]

3 个答案:

答案 0 :(得分:2)

Nikhil的第一个答案将修改原始数组,不建议这样做,因此您可以简单地做到这一点。

let students = [
      {"Name": "Priya","marks": [50, 60, 70, 80, 90]},
      {"Name": "Ankita","marks": [80, 90, 95]}
    ]

现在,我要过滤大于或等于90的标记,代码将如下所示。

students.map((student) => {
  return {...student, 
          marks: student.marks.filter((mark) => mark >= 90)
         }
}) 
// Result will be [{"Name": "Priya", "marks": [90]}, {"Name": "Ankita","marks": [90,95]}]

Spread operator将展开student,然后将其用marks key覆盖filtered marks value

如果您不使用传播运算符,

students.map((student) => student.marks.filter((mark) => mark >= 90))
// Result will be [[90],[90]]

然后,您将仅获得过滤后的值,而不是尚未应用过滤器的值。

答案 1 :(得分:2)

使用Array.filter根据条件过滤数组的值。

更新现有阵列(使用Array.forEach

let students = [{"Name": "Priya","marks": [50, 60, 70, 80, 90]},{"Name": "Ankita","marks": [80, 90, 95]}];

students.forEach(o => o.marks = o.marks.filter(v => v >= 90));
console.log(students);

创建新数组(使用Array.mapObject.assign

let students = [{"Name": "Priya","marks": [50, 60, 70, 80, 90]},{"Name": "Ankita","marks": [80, 90, 95]}];

let result = students.map(o => Object.assign({}, o, {marks : o.marks.filter(v => v >= 90)}));
console.log(result);

答案 2 :(得分:0)

您可以使用.map().filter()Object.assign()方法:

let data = [
  {"Name": "Priya","marks": [50, 60, 70, 80, 90]},
  {"Name": "Ankita","marks": [80, 90, 95]}
];

let result = data.map(
  o => Object.assign(o, {marks: o.marks.filter(v => v >= 90)})
);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }