我正在尝试创建一个函数来生成一个以UUID作为键的对象数组,以及一些嵌套对象ID的UUID。
每个游戏都将基于我导入文件的模拟对象。
该函数需要一个运动(字符串)和一个数量(数字),该运动将被分配给一个键,而数量将确定for循环迭代。
使用for循环时,每次迭代都会覆盖嵌套对象ID的UUID。
const mockGame = require('../mock-game');
const uuidv4 = require('uuid/v4');
function generateMockGames(sport, quantity) {
let games = []
for (let i = 0; i < quantity; i++) {
let game = {}
let id = uuidv4()
game[id] = {
search: mockGame.search,
query: mockGame.query,
variables: mockGame.variables,
}
game[id].search.eventId = id
game[id].search.competition.categoryName = sport
game[id].search.id = id
game[id].search.competition.categoryName = sport;
games.push(game);
}
return games;
}
const mockFootballGame = generateMockGames('football', 3);
预期结果:
[
{
'286c1911-b155-4197-bbde-64dba0b304fe': {
search: {
eventId: '286c1911-b155-4197-bbde-64dba0b304fe',
name: 'test name',
competition: {
categoryName: 'football'
}
},
query: {
id: '286c1911-b155-4197-bbde-64dba0b304fe',
competition: {
categoryName: 'football'
}
},
variables: {
name: 'test name'
}
},
{
'082a46a6-4dde-433d-8011-9e94a5ee79ff': {
search: {
eventId: '082a46a6-4dde-433d-8011-9e94a5ee79ff',
name: 'test name',
competition: {
categoryName: 'football'
}
},
query: {
id: '082a46a6-4dde-433d-8011-9e94a5ee79ff',
competition: {
categoryName: 'football'
}
},
variables: {
name: 'test name'
}
},
{
'ba911751-3ea3-40ab-9bec-c525ab2a07b9': {
search: {
eventId: 'ba911751-3ea3-40ab-9bec-c525ab2a07b9',
name: 'test name',
competition: {
categoryName: 'football'
}
},
query: {
id: 'ba911751-3ea3-40ab-9bec-c525ab2a07b9',
competition: {
categoryName: 'football'
}
},
variables: {
name: 'test name'
}
}
]
输出为:
[
{
'286c1911-b155-4197-bbde-64dba0b304fe': {
search: {
eventId: 'ba911751-3ea3-40ab-9bec-c525ab2a07b9',
name: 'test name',
competition: {
categoryName: 'football'
}
},
query: {
id: 'ba911751-3ea3-40ab-9bec-c525ab2a07b9',
competition: {
categoryName: 'football'
}
},
variables: {
name: 'test name'
}
},
{
'082a46a6-4dde-433d-8011-9e94a5ee79ff': {
search: {
eventId: 'ba911751-3ea3-40ab-9bec-c525ab2a07b9',
name: 'test name',
competition: {
categoryName: 'football'
}
},
query: {
id: 'ba911751-3ea3-40ab-9bec-c525ab2a07b9',
competition: {
categoryName: 'football'
}
},
variables: {
name: 'test name'
}
},
{
'ba911751-3ea3-40ab-9bec-c525ab2a07b9': {
search: {
eventId: 'ba911751-3ea3-40ab-9bec-c525ab2a07b9',
name: 'test name',
competition: {
categoryName: 'football'
}
},
query: {
id: 'ba911751-3ea3-40ab-9bec-c525ab2a07b9',
competition: {
categoryName: 'football'
}
},
variables: {
name: 'test name'
}
}
]
答案 0 :(得分:0)
您要在循环中将mockGame
的子对象分配给条目,而不复制它们。因此,您可以在循环中使用新的uuid继续覆盖mockGame.query.id
等,然后将mockGame.query
对象作为一个整体分配给输出。