简体   繁体   中英

From array of objects extract array of property values for items having another property equal to given value

An array is given below. I would like to get the username for every single member of this array whose team is red!

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"]
  },

];

I've tried this code:

const colorTeam = array.filter(teams=>teams.team === 'red');
console.log('teamColor:', username);

It didn't work!

As opposed to filter() + map() (two passes over the source array), one may use Array.prototype.reduce() to achieve that in a single pass (which may give certain performance gain should input array be large enough, or such filtering performed often enough):

 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%;}

If this is what you wanted? First we filter objects with team === red , then we map the array to contain username property only.

 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);

user Array.filter followed by 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)

In one line:

let newArray = array.filter((el) => el.team==="red" ? el : "").map((el) => el.username);

First, filter objects with team property named "red", then use map method to get username properties only.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM