I am trying to create a function to generate an array of objects with a UUID as the key, as well as a UUID for some of the nested object ids.
Each game will be based on a mock object which I import into the file.
The function expects a sport (string) which will get assigned to a key and a quantity (number) which will determine the for loop iterations.
When using a for loop the UUID for the nested object ids are getting overridden on each iteration.
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);
Expected result:
[
{
'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'
}
}
]
Output is:
[
{
'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'
}
}
]
You are assigning subobjects of mockGame in your loop to the entries, without copying them. So you keep overwriting mockGame.query.id etc, with a new uuid in your loop, but then assign the mockGame.query object as a whole to your output.
Related
i want to create a new array from api, but i don't know how to make it, i'm very confused in looping each array
This is each data
const group_one = [
{
name: "smash",
id: "012112"
},
{
name: "ahlan wa sahlan",
id: "123123"
},
{
name: "ahh",
id: "1231239"
},
{
name: "laki",
id: "21312"
}
];
const group_two = [
{
name: "ahh",
id: "1231239"
},
{
name: "laki",
id: "21312"
}
];
const group_three = [
{
name: "smash",
id: "012112"
},
{
name: "ahlan wa sahlan",
id: "123123"
}
];
this is the main data of api
const data = [
{
body: group_one,
group_id: "01"
},
{
body: grouop_two,
group_id: "02"
},
{
body: group_three,
group_id: "03"
}
];
export default data;
i want to create a new array like this, bcs i want to create a new object containing the group_id of each same data in the array
const newArray = [
{
name: "smash",
id: "012112",
group_id: ["01","03"]
},
{
name: "ahlan wa sahlan",
id: "123123",
group_id: ["01","03"]
},
{
name: "ahh",
id: "1231239",
group_id: ["01","02"]
},
{
name: "laki",
id: "21312",
group_id: ["01","02"]
}
];
can someone help me? with articles or codes.
thanks for helping me (sry for my bad english)
Please see below commented code:
const group01 = [
{
name: 'smash',
id: '012112'
},
{
name: 'ahlan wa sahlan',
id: '123123'
},
{
name: 'ahh',
id: '1231239'
},
{
name: 'laki',
id: '21312'
}
];
const group02 = [
{
name: 'ahh',
id: '1231239'
},
{
name: 'laki',
id: '21312'
}
];
const group03 = [
{
name: 'smash',
id: '012112'
},
{
name: 'ahlan wa sahlan',
id: '123123'
}
];
const data = [
{
body: group01,
group_id: '01'
},
{
body: group02,
group_id: '02'
},
{
body: group03,
group_id: '03'
}
];
function regroup(input) {
// USE Map FOR EASIER ITEM HANDLING.
const output = new Map();
// LOOP MAIN DATA ARRAY.
input.forEach(({body, group_id}) => {
// LOOP EACH GROUP.
body.forEach(({name, id}) => {
// USE id TO GET AN ITEM FROM output OR CREATE A NEW ONE IF IT DOES NOT EXIST.
const item = output.get(id) || {name, id, group_id: []};
// PUSH CURRENT group_id TO THE RESPECTIVE ARRAY.
item.group_id.push(group_id);
// SAVE ITEM TO OUTPUT Map AGAIN.
output.set(id, item);
});
});
// RETURN OUTPUT.
return Array.from(output.values());
}
const new_data = regroup(data);
console.log(new_data);
const beers = [
{
id: '100',
name: 'stoneys'
},
{
id: '200',
name: 'budweiser'
},
{
id: '300',
name: 'miller'
},
{
id: '400',
name: 'corona'
}
];
const people = [
{
name: 'steve',
teams: [
{
name: 'pirates',
beers: ['100']
},
{
name: 'penguins',
beers: ['300']
}
]
},
{
name: 'jim',
teams: [
{
name: 'indians',
beers: ['200']
},
{
name: 'blue jackets',
beers: ['100', '400']
}
]
}
];
let newPeople = people.map(fan => {
fan.teams.map(team => {
team.beers.map(beer => beers.filter(brand => brand.id === beer)[0])
});
});
Above is a sample I put together to best demonstrate my question. I am having trouble understanding why nested mapping (.map()) of object arrays is not allowing me to alter the nested data. When I console log results, I am either getting an "[undefined, undefined]' or the unchanged "people" array.
I would like to return the same array as "people" except replace the nested "beers" array (people.teams.beers[]) with corresponding objects from the "beers" array. Example of a successful result below:
{
name: 'steve',
teams: [
{
name: 'pirates',
beers: [
{
id: '100',
name: 'stoneys'
}
]
},
{
name: 'penguins',
beers: [
{
id: '300',
name: 'miller'
}
]
}
]
}
Array.map expects a function which takes single array element as parameter and returns a mapped value. In your case you're not returning any value from mapping functions therefore you're getting undefined twice
const beers = [
{
id: '100',
name: 'stoneys'
},
{
id: '200',
name: 'budweiser'
},
{
id: '300',
name: 'miller'
},
{
id: '400',
name: 'corona'
}
];
const people = [
{
name: 'steve',
teams: [
{
name: 'pirates',
beers: ['100']
},
{
name: 'penguins',
beers: ['300']
}
]
},
{
name: 'jim',
teams: [
{
name: 'indians',
beers: ['200']
},
{
name: 'blue jackets',
beers: ['100', '400']
}
]
}
];
let newPeople = people.map(fan => {
let teams = fan.teams.map(team => {
let beer = team.beers.map(beer => beers.filter(brand => brand.id === beer)[0]);
return { name: team.name, beers: beer }
});
return { name: fan.name, teams: teams }
});
console.log(newPeople);
Suppose there are two objects.
const a = [
{ id: '1-1-1', name: 'a111' },
{ id: '1-1-2', name: 'a112' },
{ id: '1-2-1', name: 'a121' },
{ id: '1-2-2', name: 'a122' },
{ id: '2-1-1', name: 'a211' },
{ id: '2-1-2', name: 'a212' }
]
const b = ['1-1', '1-2', '2-1']
and the result
{
'1-1':[
{ id: '1-1-1', name: 'a111' },
{ id: '1-1-2', name: 'a112' },
],
'1-2':[
{ id: '1-2-1', name: 'a121' },
{ id: '1-2-2', name: 'a122' },
],
'2-1':[
{ id: '2-1-1', name: 'a211' },
{ id: '2-1-2', name: 'a212' },
]
}
Basically, I want to group the data.
I use includes to check if the item from b to match the id from a. Then construct the new array.
This is my attempt(fiddle):
return b.map(item => a.map(jtem => {
if(jtem.id.includes(item)){
return {
[item]: jtem
}
}
}))
For somehow, it doesn't work.
and, is there a clever way to avoid the nested for loop or map function?
You can do that in following steps:
Apply reduce() on the array b
During each iteration use filter() on the the array a
Get all the items from a which starts with item of b using String.prototype.startsWith()
At last set it as property of the ac and return ac
const a = [
{ id: '1-1-1', name: 'a111' },
{ id: '1-1-2', name: 'a112' },
{ id: '1-2-1', name: 'a121' },
{ id: '1-2-2', name: 'a122' },
{ id: '2-1-1', name: 'a211' },
{ id: '2-1-2', name: 'a212' }
]
const b = ['1-1', '1-2', '2-1']
let res = b.reduce((ac,b) => {
ac[b] = a.filter(x => x.id.startsWith(b));
return ac;
},{})
console.log(res)
As suggested by #Falco is the comments that It would be better to scan over the a once as its large. So here is that version.Actually its better regarding performance
const a = [
{ id: '1-1-1', name: 'a111' },
{ id: '1-1-2', name: 'a112' },
{ id: '1-2-1', name: 'a121' },
{ id: '1-2-2', name: 'a122' },
{ id: '2-1-1', name: 'a211' },
{ id: '2-1-2', name: 'a212' }
]
const b = ['1-1', '1-2', '2-1']
let res = a.reduce((ac,x) => {
let temp = b.find(y => x.id.startsWith(y))
if(!ac[temp]) ac[temp] = [];
ac[temp].push(x);
return ac;
},{})
console.log(res)
Note: startsWith is not supported by I.E. So you can create polyfill using indexOf
if(!String.prototype.startWith){
String.prototype.startsWith = function(str){
return this.indexOf(str) === 0
}
}
I create a ticket using zendesk but I didn't know why this happens
here is node js code:
config.js
baseTicketObject: {
'comment': {
'body': null,
},
'requester': {
'name': null,
'email': null,
},
'custom_fields': [],
},
create ticket api
function createTicketObjectFromRequest(req) {
const requestBody = req.body;
console.log('requestBody', requestBody);
console.log('config.baseTicketObject', config.baseTicketObject);
const ticket = Object.assign(config.baseTicketObject, {});
//console.log('ticket', ticket);
const {
messageBody, email, name, customFields,
} = requestBody;
//console.log('ticket.custom_fields', ticket.custom_fields);
// Request must contain a name, email and body
ticket.requester.name = name;
ticket.requester.email = email;
ticket.comment.body = messageBody;
if (req.user && req.user.id) {
ticket.custom_fields.push(createCustomFieldObject(config.customFieldNameToZendeskFieldIdMapping['userId'], Number(req.user.id)));
}
Object.keys(config.customFieldNameToZendeskFieldIdMapping).forEach((fieldName) => {
if (config.customFieldNameToZendeskFieldIdMapping[fieldName] === config.customFieldNameToZendeskFieldIdMapping.userId) {
return;
}
//console.log('fieldName', fieldName);
const mappedCustomFieldId = config.customFieldNameToZendeskFieldIdMapping[fieldName];
if (mappedCustomFieldId) {
ticket.custom_fields.push(createCustomFieldObject(mappedCustomFieldId, !customFields[fieldName] ? '' : customFields[fieldName]));
}
});
return { ticket: ticket };
}
whenever I post a request the config.baseTicketObject will keep all items i pushed before like this
config.baseTicketObject { comment: { body: null },
requester: { name: null, email: null },
custom_fields: [] }
-------------------------------------
config.baseTicketObject { comment: { body: 'dgfhdgfhdgfh dgfhdfghdfg' },
requester: { name: 'test other', email: 'tranthiphuonghue96#yopmail.com' },
custom_fields:
[ { id: 360010481051, value: '' },
{ id: 360010510411, value: '' },
{ id: 360010406792, value: '' },
{ id: 360010511011, value: '' },
{ id: 360010511191, value: '' },
{ id: 360010920852, value: 'contact_support' } ] }
---------------------------------------------------------
config.baseTicketObject { comment: { body: 'dgfhdgfhdgfh dgfhdfghdfg' },
requester: { name: 'test other', email: 'tranthiphuonghue96#yopmail.com' },
custom_fields:
[ { id: 360010481051, value: '' },
{ id: 360010510411, value: '' },
{ id: 360010406792, value: '' },
{ id: 360010511011, value: '' },
{ id: 360010511191, value: '' },
{ id: 360010920852, value: 'contact_support' },
{ id: 360010481051, value: '' },
{ id: 360010510411, value: '' },
{ id: 360010406792, value: '' },
{ id: 360010511011, value: '' },
{ id: 360010511191, value: '' },
{ id: 360010920852, value: 'contact_support' } ] }
I don't know why the config.baseTicketObject like that, please help.
Reverse parameters order in Object.assing.
You have
Object.assign(config.baseTicketObject, {});
but should be
Object.assign({}, config.baseTicketObject);
Object.assign syntax
Object.assign(target, ...sources)
In your case
const ticket = Object.assign({}, config.baseTicketObject);
Edit:
Add
ticket.custom_fields = [];
after
const ticket = Object.assign({}, config.baseTicketObject);
because Object.assign create shallow copy, witch mean that ticket.custom_fields still holds reference to original array object from config.baseTicketObject.custom_fields
I want to add the children array to node where id = 52126f7d (or another). How do I do it?
var children = [
{ name: 'great-granchild3',
id: '2a12a10h'
},
{ name: 'great-granchild4',
id: 'bpme7qw0'
}
]
// json tree
var objects = {
name: 'all objects',
id:"2e6ca1c3",
children: [
{
name: 'child',
id: "6c03cfbe",
children: [
{ name: 'grandchild1',
id: "2790f59c"
},
{ name: 'grandchild2',
id: "52126f7d"
},
{ name: 'grandchild3',
id: "b402f14b"
},
{
name: 'grandchild4',
id: "6c03cff0",
children: [
{ name: 'great-grandchild1',
id: "ce90ffa6"
},
{ name: 'great-grandchild2',
id: "52f95f28"
}
]
}
]
},
{
name: 'child2',
id: "7693b310",
children: [
{ name: 'grandchild5',
id: "def86ecc"
},
{ name: 'grandchild6',
id: "6224a8f8"
}
]
}
]
}
to end up with
var objects = {
name: 'all objects',
id:"2e6ca1c3",
children: [
{
name: 'child',
id: "6c03cfbe",
children: [
{ name: 'grandchild1',
id: "2790f59c"
},
{ name: 'grandchild2',
id: "52126f7d",
children = [
{ name: 'great-granchild3',
id: '2a12a10h'
},
{ name: 'great-granchild4',
id: 'bpme7qw0'
}
]
},
{ name: 'grandchild3',
id: "b402f14b"
},
{
name: 'grandchild4',
id: "6c03cff0",
children: [
{ name: 'great-grandchild1',
id: "ce90ffa6"
},
{ name: 'great-grandchild2',
id: "52f95f28"
}
]
}
]
},
{
name: 'child2',
id: "7693b310",
children: [
{ name: 'grandchild5',
id: "def86ecc"
},
{ name: 'grandchild6',
id: "6224a8f8"
}
]
}
]
}
by finding the proper node first.
function getNodeById(id, node){
var reduce = [].reduce;
function runner(result, node){
if(result || !node) return result;
return node.id === id && node || //is this the proper node?
runner(null, node.children) || //process this nodes children
reduce.call(Object(node), runner, result); //maybe this is some ArrayLike Structure
}
return runner(null, node);
}
var target = getNodeById("52126f7d", objects);
target.children = children;
How about:
objects.children[0].children[1].children = children;