我在下面的数组中如何获取年龄大于18岁的姓名列表。
因此输出应为:["Anna", "Bob"]
friends = [{
name: 'Anna',
books: ['Bible', 'Harry Potter'],
age: 21
}, {
name: 'Bob',
books: ['War and peace', 'Romeo and Juliet'],
age: 26
}, {
name: 'Alice',
books: ['The Lord of the Rings', 'The Shining'],
age: 18
}]
我在下面尝试过
let names = friends.map((item) => {if (item.age > 18){ return item.name}});
但是我的输出低于输出
["Anna", "Bob", undefined]
答案 0 :(得分:3)
在Array.map()
之前使用Array.filter()
,因为map
总是返回一个值,如果不指定undefined
语句,则会得到return
。对于3个元素的数组,总会有3个元素的结果。
let friends = [{
name: 'Anna',
books: ['Bible', 'Harry Potter'],
age: 21
}, {
name: 'Bob',
books: ['War and peace', 'Romeo and Juliet'],
age: 26
}, {
name: 'Alice',
books: ['The Lord of the Rings', 'The Shining'],
age: 18
}]
let result = friends.filter(f => f.age > 18).map(f => f.name);
console.log(result);
答案 1 :(得分:2)
您可以使用Array.prototype.reduce
let friends = [{
name: 'Anna',
books: ['Bible', 'Harry Potter'],
age: 21
}, {
name: 'Bob',
books: ['War and peace', 'Romeo and Juliet'],
age: 26
}, {
name: 'Alice',
books: ['The Lord of the Rings', 'The Shining'],
age: 18
}];
let ans = friends.reduce((acc, val) => (val.age > 18 && acc.push(val.name),acc), []);
console.log(ans);
答案 2 :(得分:1)
您将undefined
作为names
数组中的最后一项,因为map
函数用于转换数组中被调用的每个项,然后返回每个转换后的值。
如果在长度为3的数组上调用它,则map
函数将返回相同长度的数组。由于您只从年龄大于18的map
函数返回那些名称,而年龄不大于18的最后一个对象返回了您的名字,因此您无需对其进行转换并返回其name属性,因此得到undefined
。
获得期望结果的一种方法是使用filter
函数过滤掉年龄不大于18岁的对象,然后在该过滤后的数组上调用map
函数。
在上述方法中,您的代码将首先在friends
数组上进行迭代,然后在经过过滤的数组上进行迭代。
您可以使用friends
函数来获得所需的结果并仅在reduce
数组上迭代一次
const friends = [{
name: 'Anna',
books: ['Bible', 'Harry Potter'],
age: 21
}, {
name: 'Bob',
books: ['War and peace', 'Romeo and Juliet'],
age: 26
}, {
name: 'Alice',
books: ['The Lord of the Rings', 'The Shining'],
age: 18
}];
const res = friends.reduce((acc, curr) => (curr.age > 18 && acc.push(curr.name), acc), []);
console.log(res);
答案 3 :(得分:0)
let friends = [{ name: 'Anna', books: ['Bible', 'Harry Potter'], age: 21 }, { name: 'Bob', books: ['War and peace', 'Romeo and Juliet'], age: 26 }, { name: 'Alice', books: ['The Lord of the Rings', 'The Shining'], age: 18 }]
let ages = friends.filter((friends) => friends.age>18)
let finalResult = ages.map(fun => ages.name)
console.log(finalResult)
使用Array.filter()