gpt4 book ai didi

javascript - 从对象数组返回名称数组

转载 作者:行者123 更新时间:2023-11-28 12:51:45 25 4
gpt4 key购买 nike

我知道如何循环访问一个对象并打印出我想要的值数组,但我无法按照我想要的顺序打印它。

**问题是:**

给定一组游戏结果记录,通过返回姓名数组来确定所有玩家是谁。

数组应按名称的出现方式排序。

输入示例:

[
{ winner: 'Alishah', loser: 'Bob', loser_points: 3 },
{ winner: 'Maria', loser: 'Xu Jin', loser_points: 1 },
{ winner: 'Elise', loser: 'Bob', loser_points: 2 },
{ winner: 'Elise', loser: 'Maria', loser_points: 4 },
{ winner: 'Alishah', loser: 'Maria', loser_points: 2 },
{ winner: 'Maria', loser: 'Xu Jin', loser_points: 3 },
{ winner: 'Xu Jin', loser: 'Elise', loser_points: 2 }
]

预期结果:

['艾莉莎', '鲍勃', '玛丽亚', '徐进', '伊莉丝']

**我到目前为止的代码:**

let data = [
{ winner: 'Alishah', loser: 'Bob', loser_points: 3 },
{ winner: 'Maria', loser: 'Xu Jin', loser_points: 1 },
{ winner: 'Elise', loser: 'Bob', loser_points: 2 },
{ winner: 'Elise', loser: 'Maria', loser_points: 4 },
{ winner: 'Alishah', loser: 'Maria', loser_points: 2 },
{ winner: 'Maria', loser: 'Xu Jin', loser_points: 3 },
{ winner: 'Xu Jin', loser: 'Elise', loser_points: 2 }
];


console.log(main(data));

最佳答案

您可以使用.flatMap()Set()为此:

let data = [
{ winner: 'Alishah', loser: 'Bob', loser_points: 3 },
{ winner: 'Maria', loser: 'Xu Jin', loser_points: 1 },
{ winner: 'Elise', loser: 'Bob', loser_points: 2 },
{ winner: 'Elise', loser: 'Maria', loser_points: 4 },
{ winner: 'Alishah', loser: 'Maria', loser_points: 2 },
{ winner: 'Maria', loser: 'Xu Jin', loser_points: 3 },
{ winner: 'Xu Jin', loser: 'Elise', loser_points: 2 }
];

const res = [...new Set(data.flatMap(x=>[x.winner, x.loser]))]
console.log( res )

说明:

  • 使用.flatMap()方法我们首先会得到一个数组的数组。这里的内部数组将是 winnerloser 名称的数组。
  • 然后我们将展平数组以获得所有玩家姓名的单个数组。
  • 最后使用[...new Set(array)]我们将在数组中获得不同的名称以实现所需的结果。

关于javascript - 从对象数组返回名称数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60888184/

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