nodejs - convert one obj to some objects - node.js

I have one obj that I received from the client,
const record = {
"date":"2021-09-20",
"startAt":"10:00",
"endAt":"16:00",
"employeeId": [5,2],<==
"projectId":[50,48],<==
"notes":"blahhh"
}
I want to convert it to some objects, same details , but I want for example
employeeId 5 worked in two projects, 50 and 48
I want to have two objects with same details but the employeeId is 50 and the projectId : first object with 50 and the sec obj with 48
{
....
"employeeId": [5],<== //first emplyee
"projectId":[50],<== // first project
....
}
{
....
"employeeId": [5],//first emplyee
"projectId":[48], // sec project
...
}
{
....
"employeeId": [2],//sec employee
"projectId":[50], //first project
....
}
{
....
"employeeId": [2],//sec employee
"projectId":[48], //sec project
....
}
thank you for helping me

You can do for example:
const record = {
date: "2021-09-20",
startAt: "10:00",
endAt: "16:00",
employeeId: [5, 2],
projectId: [50, 48],
notes: "blahhh",
};
const records = record.employeeId
.map((employeeId) =>
record.projectId.map((projectId) => ({
...record,
employeeId: [employeeId],
projectId: [projectId]
}))
)
.flat();
console.log(records);

1- Extract all of keys which have array values
let arrayKeys = Object.entries(record).filter(([key, value]) => typeof value === 'object' && Array.isArray(value))
2- Create your default object with default keys:
let defaultObj = Object.entries(record).reduce((obj, [key, value]) => {
if(!typeof value === 'object' || !Array.isArray(value)) {
obj[key] = value
}
return obj;
}, {})
3- Create a function which fill an array with your final objects recursively:
function addKeys(array, obj, keys) {
if(!keys.length) {
array.push(obj);
return;
}
let [key, values] = keys.pop();
values.forEach(val => {
obj[key] = [val];
addKeys(array, {...obj}, [...keys])
});
}
Full code:
const record = {
"date":"2021-09-20",
"startAt":"10:00",
"endAt":"16:00",
"employeeId": [5,2],
"projectId":[50,48, 60, 70],
"notes":"blahhh",
"extraArrayKey": ['a', 'b']
}
let arrayKeys = Object.entries(record).filter(([key, value]) => typeof value === 'object' && Array.isArray(value))
let defaultObj = Object.entries(record).reduce((obj, [key, value]) => {
if(!typeof value === 'object' || !Array.isArray(value)) {
obj[key] = value
}
return obj;
}, {})
function addKeys(array, obj, keys) {
if(!keys.length) {
array.push(obj);
return;
}
let [key, values] = keys.pop();
values.forEach(val => {
obj[key] = [val];
addKeys(array, {...obj}, [...keys])
});
}
let output = [];
addKeys(output, defaultObj, arrayKeys)
console.log(output)

Related

Discord.js | How to create a limit of .addFields objects, creating a list with .addFields with different value of an Array?

I created a script to do tests, I want to make a listing with 4 objects inside the .addfields, if you have more than 4, create an embed throwing other data in the objects inside the .addfields in it.
const Command = require("../../structures/Command");
const { EmbedBuilder, ModalBuilder, TextInputComponent, ButtonBuilder, ButtonStyle, ApplicationCommandType, ActionRowBuilder, SelectMenuOptionBuilder, SelectMenuBuilder} = require('discord.js');
module.exports = class extends Command {
constructor(client) {
super(client, {
name: 'shop',
description: 'shop',
type: ApplicationCommandType.ChatInput
});
};
run = async (interaction) => {
let listItems = ['Whinds', 'Freeway', 'Teste', 'Maria'];
const embed = [];
let i = 0;
listItems.forEach(e => {
if (!embed[Math.floor(i / 60)]) {
embed.push(new EmbedBuilder()
.setDescription(`testando`)
.addFields(
listItems.map(item => (
{
name: `${item[i]} [R$ ${item[i]}]`, value: `${item[i]}`}
))
)
);
}
i++;
})
console.log(embed)
embed.forEach(e => {
interaction.reply({embeds: [e] });
})
}
}
I would like support, how can I make this listing system with a maximum of 4 objects in the embed addfields.

writefilesync not writing all variables to a json file

I have this code:
circular = () => { //fix circular stuff for json.stringify
seen = new WeakSet();
return (key, value) => {
if (typeof value === 'object' && value !== null) {
if (seen.has(value)) {
return;
}
seen.add(value);
}
return value;
};
};
var gameon = 1;
var fighter1 = {"userid":"97","username":"john","items":{},"ailments":{}};
var fighter2 = {"userid":"91","username":"james","items":{},"ailments":{}};
var resume = 30;
all = {gameon:gameon,fighter1:fighter1,fighter2:fighter2,resume:resume,inturn:fighter1,outturn:fighter2};
fs.writeFileSync(file,JSON.stringify(all,circular()),{encoding:'utf8',flag:'w'});
I expect to have the next output written to file:
{
"gameon":1,
"fighter1":{
"userid":"97",
"username":"john",
"items": {},
"ailments":{}
},
"fighter2":{
"userid":"91",
"username":"james",
"items":{},
"ailments":{}
},
"resume":"",
"inturn":{
"userid":"97",
"username":"john",
"items":{},
"ailments":{}
},
"outturn":{
"userid":"91",
"username":"james",
"items":{},
"ailments":{}
}
but this is what I get instead:
{
"gameon":1,
"fighter1":{
"userid":"97",
"username":"john",
"items":{},
"ailments":{}
},
"fighter2":{
"userid":"91",
"username":"james",
"items":{},
"ailments":{}
},
"resume":""
}
Please notice how the string truncates after "resume" like it couldn't read the variables fighter1 and fighter2 despite it could do it for the first iteration.
Why is that?
Thank you.

GraphQL Resolver returns error "Cannot read forEach of Undefined"

I have a graphql endpoint that I'm running a query against, and I'm building my resolver that is massaging the data before returning to the client. My query is this:
query getTransactions($transID: String!, $confidence: Float) {
transactions(parentID: $transID, confidence: $confidence) {
id
childrens {
id
name
email
phone
age
connectionInfo {
type
confidence
}
}
name
email
phone
age
}
}
and my resolver is currently looking like this:
const getTransactions = (args: any): any => {
const { parentID, confidence } = args;
const trxs = transactions.filter(t => {
return t.id === parentID;
});
let finalChildrens: any[] = [];
trxs.forEach(t => {
finalChildrens.concat(filteredChildren(t));
});
trxs.concat(finalChildrens);
return trxs;
};
const filteredChildren = (t: any): any[] => {
log.debug({ typeCheck: typeof t.childrens, children: t.childrens });
let outputChildren: any[] = [];
if (typeof t.childrens !== undefined) {
t.childrens.forEach((c1: any) => {
if (typeof c1.childrens !== undefined) {
outputChildren.concat(filteredChildren(c1));
outputChildren.push(c1);
} else {
outputChildren.push(c1);
}
});
return outputChildren;
} else {
return ['no child'] as any[];
}
};
The issue I'm facing is that I'm continually getting this error either in the client or graphiql is this:
"Cannot read property 'forEach' of undefined"
I want to say that it has to do with either the forEach in filteredChildren or inside the resolver itself. I'm going through these "gymnastics" in order to get a flat array that is retrieved recursively from the underlying data. How would someone check the array to see if it's filled or not? (or in this case, if the array exists at all?)
The condition typeof t.childrens !== undefined is always true. You should either use typeof t.childrens !== "undefined" or t.childrens !== undefined.

converting excel(.xlsx) file to JSON

I have excel sheet called sampledata.xlsx which i converted into json and console.log to print this data.
server.js
var xlsx2json = require('xlsx2json')
xlsx2json(
'sampledata.xlsx',
{
dataStartingRow: 2,
mapping: {
'name': 'B',//name
'sku': 'C',//unit price //sku
'quantity': 'D',//quantity
}
}).then(jsonArray => {
// [
// {"col_1": "Barton LCC", "col_2": "30", "col_3": "86.69"}
// ]
//console.log(jsonArray);
});
with the help of this doc.
What i want to do here is,in my sampledata.xlsx file i have more data like flat,address,price,etc here i already don't know which fields are present in my excel sheet but i want all that to be console.log.How could i do this is there any way to do this.
import xlsx2json from 'xlsx2json';
OR
const xlsx2json = require('xlsx2json');
const excel2json = [
(req, res, next) => {
xlsx2json(req.body.file.path)
.then(result => result[0])
.reduce((object, item, index) => {
if (index === 0) {
object.mapper = item; // eslint-disable-line no-param-reassign
return object;
}
const data = {};
Object.keys(item).forEach((key) => {
data[object.mapper[key]] = item[key];
});
object.data.push(data);
return object;
}, { mapper: {}, data: [] })
.then(excel => console.log(excel)) // this gives json as output
.catch(err => next(err));
},
];
npm install xlsx-to-json-lc --save
npm install xls-to-json-lc --save
var exceltojson = require("xls-to-json-lc");
exceltojson({
input: "pass the input excel file here (.xls format)"
output: "if you want output to be stored in a file"
sheet: "sheetname", // specific sheetname inside excel file (if you have multiple sheets)
lowerCaseHeaders:true //to convert all excel headers to lowr case in json
}, function(err, result) {
if(err) {
console.error(err);
} else {
console.log(result);
//result will contain the overted json data
}
});

Firebase Flashlight (ElasticSearch) filtering, sorting, pagination

I am using Flashlight Firebase plugin
I am using this example and it's working fine
In the example you can see example.js file have method for query as below
// display search results
function doSearch(index, type, query) {
var ref = database.ref().child(PATH);
var key = ref.child('request').push( { index: index, type: type, query: query } ).key;
ref.child('response/'+key).on('value', showResults);
}
above function returning me the results when I pass values like following JSON
{ index: index, type: type, query: query }
It returning me nothing when i am trying to pass values like following JSON
{ index: index, type: type, query: { "from" : 1, "size" : 5 , "query": query }
but the following ElasticSearch API returning me the result
http://localhost:9200/firebase/user/_search?q=*mani*&pretty&size=5&from=1
and How do i filtering the query using Flashlight like following
{
"query": {
"filtered": {
"query": {
"query_string": {
"query": "drama"
}
},
"filter": {
//Filter to apply to the query
}
}
}
}
I am using following security rules
{
"rules": {
".read": false,
".write": false,
"search": {
"request": {
"$recid": {
// I can only read records assigned to me
".read": "auth.id === data.child('id').val() || auth.uid === data.child('id').val()",
// I can only write new records that don't exist yet
".write": "!data.exists() && (newData.child('id').val() === auth.id || newData.child('id').val() === auth.uid)",
".validate": "newData.hasChildren(['query', 'index', 'type'])",
"index": {
// accepts arrays or strings
".validate": "(newData.isString() && newData.val().length < 1000) || newData.hasChildren()",
"$child": {
".validate": "newData.isString() && newData.val().length < 1000"
}
},
"type": {
// accepts arrays or strings
".validate": "(newData.isString() && newData.val().length < 1000) || newData.hasChildren()",
"$child": {
".validate": "newData.isString() && newData.val().length < 1000"
}
},
"query": {
// structure of the query object is pretty open-ended
".validate": "newData.isString() || newData.hasChildren()"
},
"$other": {
".validate": false
}
}
},
"response": {
"$recid": {
// I can only read/write records assigned to me
".read": "auth.id === data.child('id').val() || auth.uid === data.child('id').val()",
".write": "auth.id === data.child('id').val() || auth.uid === data.child('id').val()",
// Assumes that Flashlight will be writing the records using a secret or a token that has admin: true
// The only thing a logged in user needs to do is delete results after reading them
".validate": false
}
}
}
}
}
Please let me know how to perform complex queries and filtering with Flashlight
Finally I did it myself
here is the solution
You need to update SearchQueue.js
_process: function (snap) {
var dat = snap.val();
var key = snap.key;
if (this._assertValidSearch(key, dat)) {
// get your query string
var q = dat.query.query;
console.log('search', "test", JSON.stringify(dat, null, 2));
// build your ES query
//var q1 = {"query":{"match":{"_all":q}}};
// Perform (a very simple) ElasticSearch query
this.esc.search({
index: dat.index,
type: dat.type,
// add options
from : dat.query.from,
size : dat.query.size,
// add ES Query
//body : q1
q:dat.query.query
}, function (error, response) {
if (error) {
this._reply(key, {error: error, total: 0});
} else {
this._reply(key, response);
}
}.bind(this));
}
}
and update Example.js
// display search results
function doSearch(index, type, query) {
var ref = database.ref().child(PATH);
var jsonOBJ = {
index: index,
type: type,
query: { size:1, from:0, query:query},
};
var key = ref.child('request').push(jsonOBJ).key;
console.log('search', key, JSON.stringify(jsonOBJ, null, 2));
ref.child('response/'+key).on('value', showResults);
}

Resources