[英]From array of objects extract array of property values for items having another property equal to given value
下面给出了一个数组。 我想获取该数组中团队为红色的每个成员的用户名!
const array = [
{
username: "john",
team: "red",
score: 5,
items: ["ball", "book", "pen"]
},
{
username: "becky",
team: "blue",
score: 10,
items: ["tape", "backpack", "pen"]
},
{
username: "susy",
team: "red",
score: 55,
items: ["ball", "eraser", "pen"]
},
{
username: "tyson",
team: "green",
score: 1,
items: ["book", "pen"]
},
];
我试过这段代码:
const colorTeam = array.filter(teams=>teams.team === 'red');
console.log('teamColor:', username);
它没有用!
与filter()
+ map()
(源数组上的两次传递)相反,可以使用Array.prototype.reduce()
来实现单次传递(如果输入数组足够大,这可能会带来一定的性能增益,或经常执行此类过滤):
const array = [{username:"john",team:"red",score:5,items:["ball","book","pen"]},{username:"becky",team:"blue",score:10,items:["tape","backpack","pen"]},{username:"susy",team:"red",score:55,items:["ball","eraser","pen"]},{username:"tyson",team:"green",score:1,items:["book","pen"]}], redTeamNames = array.reduce((acc, {username, team}) => (team == 'red' && acc.push(username), acc), []) console.log(redTeamNames)
.as-console-wrapper{min-height:100%;}
如果这是你想要的? 首先我们用team === red
过滤对象,然后我们 map 数组只包含username
属性。
const array = [ { username: "john", team: "red", score: 5, items: ["ball", "book", "pen"] }, { username: "becky", team: "blue", score: 10, items: ["tape", "backpack", "pen"] }, { username: "susy", team: "red", score: 55, items: ["ball", "eraser", "pen"] }, { username: "tyson", team: "green", score: 1, items: ["book", "pen"] }, ]; const colorTeam = array.filter(teams=>teams.team === 'red').map(user=>user.username); console.log('teamColor:', colorTeam);
用户Array.filter
后跟Array.map
:
const array=[{username:"john",team:"red",score:5,items:["ball","book","pen"]},{username:"becky",team:"blue",score:10,items:["tape","backpack","pen"]},{username:"susy",team:"red",score:55,items:["ball","eraser","pen"]},{username:"tyson",team:"green",score:1,items:["book","pen"]}]; let result = array.filter(({team}) => team === "red").map(({username}) => username) console.log(result)
在一行中:
let newArray = array.filter((el) => el.team==="red" ? el : "").map((el) => el.username);
首先,过滤具有名为“red”的团队属性的对象,然后使用 map 方法仅获取用户名属性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.