gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 11:18:59 25 4
gpt4 key购买 nike

考虑到以下包含多个对象的数组,我尝试在一个数组中获取特定值。说得委婉点,我想提取“红色”团队中人员的名字。

// 
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)►[迈克,艾莉]

最佳答案

一种方法是使用 Array.prototype.filterArray.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);

关于javascript - 从数组中的对象获取特定值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50534153/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com