【问题标题】:getting specific values from objects within arrays从数组中的对象获取特定值
【发布时间】:2018-11-05 03:29:48
【问题描述】:

考虑到下面的数组,其中包含多个对象,我试图在一个数组中获取特定值。说白了,我想提取“红”队中的人的名字。

// 
    const array = [
      {
        username: "Mike",
        team: "red",
        score: 20,
     items: ["bat", "book", "gloves"]
  },
  {
    username: "Moe",
    team: "blue",
    score: 30,
    items: ["cellphone", "backpack", "cards"]
  },
  {
    username: "Ellie",
    team: "red",
    score: 15,
    items: ["ball", "canteen", "crayon"]
  },
  {
    username: "little_joe",
    team: "green",
    score: 1,
    items: ["book", "pencil"]
  },

];

//using filter method :

const filterArray=array.filter((num)=>{ if (num.team==="red" ){ return num.username}});
console.log(filterArray);

//result : an array including two objects full of unwanted values.

我应该怎么做才能得到一个只有所需值的数组(而不是两个大对象)?

我正在尝试获取这样的数组: (2)►[迈克,艾莉]

【问题讨论】:

    标签: javascript arrays object filter


    【解决方案1】:

    一种方法是使用Array.prototype.filter 和Array.prototype.map。但是,首选方法是使用Array.prototype.reduce,因为它会更有效。

    像这样:

    const array = [{
        username: "Mike",
        team: "red",
        score: 20,
        items: ["bat", "book", "gloves"]
      },
      {
        username: "Moe",
        team: "blue",
        score: 30,
        items: ["cellphone", "backpack", "cards"]
      },
      {
        username: "Ellie",
        team: "red",
        score: 15,
        items: ["ball", "canteen", "crayon"]
      },
      {
        username: "little_joe",
        team: "green",
        score: 1,
        items: ["book", "pencil"]
      },
    
    ];
    
    const newArray = array.reduce((n, val) => {
      if(val.team == "red") n.push(val.username);
      return n;
    }, []);
    
    console.log(newArray);

    【讨论】:

    • 这很好,但是为什么这种噱头使用三元运算符val.team == "red" ? n.push(val.username) : null;而不是简单的if(val.team == "red") n.push(val.username);?
    • @jedzej 你是对的。我不应该为了三元而使用三元。答案已更新。谢谢。
    【解决方案2】:

    filter 不返回回调返回的值,它只是检查它是否真实,并使用它来决定是否返回数组元素。

    您可以分两步完成。先用filter得到team === "red"的元素,再用map提取username:

    const filterArray = array.filter(num => num.team === "red").map(num => num.username);
    

    您也可以使用reduce 一步完成,我将把它作为练习留给读者。

    【讨论】:

      【解决方案3】:

      根据@Barmar 的建议,这是使用reduce 的版本:

      const redTeamPeople = array.reduce((people, { team, username }) => {
        if (team === "red") {
          people.push(username);
        }
      
        return people;
      }, []);
      

      【讨论】:

      • 这是首选方法。考虑到包含大量数据的非常大的数组,更简洁、更快。
      猜你喜欢
      • 2019-10-08
      • 2022-11-29
      • 2015-06-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-17
      • 1970-01-01
      相关资源
      最近更新 更多