将两个字符串数组合并到一个对象数组

时间:2017-11-26 19:08:46

标签: javascript arrays mapreduce

我有两个看起来像这样的数组:

const players = ["id1", "id2", "id3", "id4"]
const games = ["gid1", "gid2"]

我需要返回一个如下所示的数组:

const newArray = [
  {playerId: "id1", gameId: "gid1"}, {playerId: "id1", gameId: "gid2"},
  {playerId: "id2", gameId: "gid1"}, {playerId: "id2", gameId: "gid2"},
  {playerId: "id3", gameId: "gid1"}, {playerId: "id3", gameId: "gid2"},
  {playerId: "id4", gameId: "gid1"}, {playerId: "id4", gameId: "gid2"}
]

实现这一目标的最佳方法是什么?我一直在尝试将map和reduce组合在一起,但似乎无法弄明白。

4 个答案:

答案 0 :(得分:3)

使用Array.reduce()Array.forEach()函数:

const players = ["id1", "id2", "id3", "id4"]
const games = ["gid1", "gid2"]

const result = players.reduce((r, p_id) => {
    games.forEach((g_id) => r.push({playerId: p_id, gameId: g_id}));
    return r;
}, []);

console.log(result);

答案 1 :(得分:3)

您想要创建笛卡尔数组。你可以像这样执行它;

var newArray = [];
for (var i = 0; i < players.length; i++) {
    for (var l = 0; l < games.length; l++) {
        var merged = {playerId: players[i], gameId: games[l]};
        newArray.push(merged);
    }
}

答案 2 :(得分:1)

这是使用es6 for ... of

的解决方案
const players = ['id1', 'id2', 'id3', 'id4']
const games = ['gid1', 'gid2']
let newArray = []

for (let game of games) {
   for (let player of players) {
       newArray.push({playerId: player, gameId: game})
       }
    }

答案 3 :(得分:0)

这是对功能方法的不同看法,它将代码分解为更小的部分:

const players = ["id1", "id2", "id3", "id4"]
const games = ["gid1", "gid2"];

const flatten = arrs => [].concat(...arrs);
const getGame = (id, gid) => ({ playerId: id, gameId: gid });
const getGames = games => id => games.map(gid => getGame(id, gid));
const output = flatten(players.map(getGames(games)));

console.log(output)