【问题标题】:How can I return the value of a key based on a different value in a dictionary [duplicate]如何根据字典中的不同值返回键的值[重复]
【发布时间】:2022-01-17 13:56:59
【问题描述】:
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 filterArray = array.filter(user3 => {
  return user3.team === "red";
})

【问题讨论】:

    标签: javascript arrays dictionary filter


    【解决方案1】:

    您可以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"]}];
    
    
    const filterArray = array.filter(user3 => {
      return user3.team === "red";
    })
    
    const onlyNames = filterArray.map(u => u.username)
    
    console.log(onlyNames)

    【讨论】:

      【解决方案2】:

      由于filter 方法的结果是一个数组,您可以将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 filterArray = array.filter(({team}) => team === "red").map(({username}) => username)
      
      console.log(filterArray)

      【讨论】:

        猜你喜欢
        • 2019-06-26
        • 1970-01-01
        • 1970-01-01
        • 2013-05-11
        • 2020-10-20
        • 2012-07-08
        • 2020-04-16
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多