从数组中的对象获取特定值

时间:2018-05-25 17:22:09

标签: javascript arrays object filter

考虑到下面包含几个对象的数组,我试图在一个单独的数组中获取特定的值。要巧妙地说,我想要提取出#34; red&#34中的人的名字。 ;队。

// 
    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)►[麦克,埃利]

3 个答案:

答案 0 :(得分:1)

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

您可以分两步完成。首先使用filter获取team === "red"的元素,然后使用map提取username

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

您也可以使用reduce一步完成,我会将其留给读者练习。

答案 1 :(得分:1)

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

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

  return people;
}, []);

答案 2 :(得分:1)

执行此操作的一种方法是使用$ cat /etc/issue CentOS release 6.9 (Final) Array.prototype.filter。但是,首选的方式是使用Array.prototype.map,因为它会更有效率。

像这样:



Array.prototype.reduce




相关问题