Is there a shorter way to write the below code? - javascript

I'm wondering if there is another shorter way to write the below code:
let playerListQuery = {
variables = {
input: {
pagination,
order: { field: PlayerOrderField.CreatedAtDesc },
where: {
// some others...
},
},
}
};
function updateSearch(value) {
if (!value) return;
playerListQuery.variables = {
...playerListQuery.variables,
input: {
...playerListQuery.variables.input,
where: {
...playerListQuery.variables.input.where,
or: [
{ nameContains: searchValue },
{
teamHas: [
{
or: [
{ nameContains: searchValue },
{ addressContains: searchValue },
],
},
],
},
],
},
},
};
}
As you can see I'm only interested to change the where field in updateSearch.
Is there a shorter way?

You could do a deep copy of your query then send the modified copy.
Something like so:
function updateSearch(value) {
if (!value) return;
const newQuery = deepCopy(playerListQuery);
newQuery.variables.input.where = { /* *** */ };
return newQuery;
}
As for the function that does the deep copy, if your JS object is serializable, JSON.parse(JSON.stringify(yourObject)) is a quick and easy way to deep copy
If you have more complex needs, you could look into libraries (e.g.: lodash's cloneDeep function).

Related

Logic App/JavaScript - Remove Matching Values

I have two data sources. Data Source 1 is basically a list of Projects and Users assigned to those Projects. Data Source 2 is a list of Users that I want to remove from the Projects in Data Source 1.
Data Source 1:
[
{
"db1Project":[
{
"projectCode":"1",
"assignment":{
"db1User":[
{
"assignee":"wantzc"
},
{
"assignee":"michelles"
}
]
}
},
{
"projectCode":"2",
"assignment":{
"db1User":[
{
"assignee":"stallinga"
},
{
"assignee":"domanl"
},
{
"assignee":"brantleyd"
}
]
}
},
{
"projectCode":"3",
"assignment":{
"db1User":[
{
"assignee":"cinnamonk"
}
]
}
}
]
}
]
I want to match "assignee" from Data Source 1 with "sponsor" in Data Source 2.
Data Source 2:
[
{
"db2Users":[
{
"sponsor":"wantzc"
},
{
"sponsor":"patem"
},
{
"sponsor":"stallinga"
},
{
"sponsor":"oliviaa"
},
{
"sponsor":"brantleyd"
}
]
}
]
Then remove non-matching "assignee" and generate below output:
Desired Output:
[
{
"db1Project":[
{
"projectCode":"1",
"assignment":{
"db1User":[
{
"assignee":"wantzc"
}
]
}
},
{
"projectCode":"2",
"assignment":{
"db1User":[
{
"assignee":"stallinga"
},
{
"assignee":"brantleyd"
}
]
}
}
]
}
]
Can this be done using Logic App only? If not, how to do this using JavaScript?
This is a little bit of a verbose way to do it in Javascript, but the idea is relatively simple:
Create a map of the users you're looking for so you have an O(1) lookup instead of O(n) lookup each time
Filter the users list for each project to only contain users found in the db2Users list
Add the project to the new results set if any db1Users remain after step 2
This will take 1 pass through your original array, so it's an efficient, yet simple algorithm to do what you're trying to do.
let data = [{"projectCode":"1","assignment":{"db1User":[{"assignee":"wantzc"},{"assignee":"michelles"}]}},{"projectCode":"2","assignment":{"db1User":[{"assignee":"stallinga"},{"assignee":"domanl"},{"assignee":"brantleyd"}]}},{"projectCode":"3","assignment":{"db1User":[{"assignee":"cinnamonk"}]}}];
let db2Users = [{"sponsor":"wantzc"}, {"sponsor":"patem"}, {"sponsor":"stallinga"}, {"sponsor":"oliviaa"}, {"sponsor":"brantleyd"}];
let db2UsersMap = db2Users.reduce((res, curr) => {
res[curr.sponsor] = true;
return res;
}, {});
let filteredProjects = data.reduce((res, project) => {
let currProjUsers = project.assignment.db1User;
project.assignment.db1User = currProjUsers.filter((user) => db2UsersMap[user.assignee]);
if (project.assignment.db1User.length > 0) { res.push(project); }
return res;
}, []);
console.log(filteredProjects);

How to add dynamic elements to an object in typescript

I am sorry if I am asking a very basic question, I have done some research over the internet but not getting anything useful.
I have a typescript object like :
var productIds=["one","two","three"];
let searchfilter = {
or: [{
id: { match:productids['0'] }
},{
id: { match:productids['1'] }
},{
id: { match:productids['2'] }
}]
};
My productIds can be dynamic and may hold different counts of values.
How can I create the same structure for a dynamic number of values. I tried forEach, but not sure about the syntax.
productids.forEach(function(value){
// not sure if this is right syntax, I am not getting desired results.
searchfilter.or = { id: { match:value }};
});
Can you help me with it?
You can create your full or array with a simple .map() :
var productIds = ["1", "2", "3"];
let searchfilter = {
or : productIds.map( n => ({ id : { match : productIds[n] } }))
};
However Mongo (which I believe you are using) has a $match method that's made to match a list :
{
$match: {
productIds: {
$in: productIds
}
}
}
I'll keep it as simple as I can
var productIds=["one","two","three"];
let searchfilter = productIds.map(p => {
return {id: { match: p }};
});
// function
addNewProduct(id: string) {
this.searchfilter.push({id: { match: id }});
}

Get an object property name of a a nexted array

I'm pretty new to JavaScript and am wondering if I do it the correct way.
Consider this object:
const pageLinks = {
tickets: [
{ to: "/tickets/mytickets", },
{ to: "/tickets/newticket", },
{ to: "/tickets/followup", }
],
home: [
{ to: "/home/dashboard", }
],
about: [
{ to: "/about/author", }
]
}
When a user requests the route /tickets/followup I would like it to return tickets. This code, my first one ever, does exactly that:
const to = { path: '/tickets/followup' }
for (let page in pageLinks) {
let links = pageLinks[page]
links.forEach(element => {
if (element.to === to.path) {
console.log(page)
}
});
}
My question: is this the correct way of doing it? Or would it be better to use a filter() method?
Amusing each path has one destination page it would be faster to use the paths as keys and pages as values. This way lookup based upon path is simple and fast.
const pageLinks = {
tickets: [
{ to: "/tickets/mytickets", },
{ to: "/tickets/newticket", },
{ to: "/tickets/followup", }
],
home: [
{ to: "/home/dashboard", }
],
about: [
{ to: "/about/author", }
]
};
const routes = {};
for (const page in pageLinks) {
const links = pageLinks[page];
links.forEach(link => routes[link.to] = page);
}
console.log(routes);
const to = { path: '/tickets/followup' };
console.log(routes[to.path]);
In my opinion, the "correct way", or the "best way" of doing something is really relative. If your code solves the problem (and it does), it's fine. There are infinite ways of solving the same problem. Other two ways:
Using Object.keys and array.map:
const to = { path: '/tickets/followup' }
Object.keys(pageLinks).map(page => pageLinks[page].map(link => {
if (link.to == to.path) console.log(page)
}));
Using array.find:
const to = { path: '/tickets/followup' }
let found = Object.keys(pageLinks).find(page => pageLinks[page].find(link => link.to == to.path));
console.log(found);

I am trying to check if given value exist as key in array of objects

I am trying to check if given value exist as key in array of objects
var obj = [{
tapCount1: '10'
}, {
tapCount2: '500'
}, {
tapCount3: '1250'
}, {
tapCount4: '1250'
}, {
wtOfSample: '41.00'
}, {
initialVolume: '66.0'
}, {
tapCountvol1: '60.0'
}, {
tapCountvol2: '53.0'
}, {
tapCountvol3: '52.0'
}, {
tapDensity: '0.788'
}, {
compressibilityIndex: '21.212'
}, {
hausnerRatio: '1.269'
}];
i had use below code
if (arrTDTData.hasOwnProperty("tapCount1") == false) {
count1 = 0;
} else {
count1 = arrTDTData.tapCount1;
}
i want to check if key is equal tapCount1 then it will return true else flase```
If you want to check if there is an object in the array that has tapCount1 key, you can use some().
The some() method tests whether at least one element in the array
passes the test implemented by the provided function. It returns a
Boolean value.
var obj = [{"tapCount1":"10"},{"tapCount2":"500"},{"tapCount3":"1250"},{"tapCount4":"1250"},{"wtOfSample":"41.00"},{"initialVolume":"66.0"},{"tapCountvol1":"60.0"},{"tapCountvol2":"53.0"},{"tapCountvol3":"52.0"},{"tapDensity":"0.788"},{"compressibilityIndex":"21.212"},{"hausnerRatio":"1.269"}];
var result = obj.some(o => "tapCount1" in o);
console.log(result);
Use includes with map and Object.keys (and reduce to flatten the array):
var obj = [{tapCount1:'10'},{tapCount2:'500'},{tapCount3:'1250'},{tapCount4:'1250'},{wtOfSample:'41.00'},{initialVolume:'66.0'},{tapCountvol1:'60.0'},{tapCountvol2:'53.0'},{tapCountvol3:'52.0'},{tapDensity:'0.788'},{compressibilityIndex:'21.212'},{hausnerRatio:'1.269'}];
const res = obj.map(Object.keys).reduce((acc, curr) => acc.concat(curr)).includes("tapCount1");
console.log(res);
You can also use some on the array itself with hasOwnProperty (to avoid scanning the prototype):
var obj = [{tapCount1:'10'},{tapCount2:'500'},{tapCount3:'1250'},{tapCount4:'1250'},{wtOfSample:'41.00'},{initialVolume:'66.0'},{tapCountvol1:'60.0'},{tapCountvol2:'53.0'},{tapCountvol3:'52.0'},{tapDensity:'0.788'},{compressibilityIndex:'21.212'},{hausnerRatio:'1.269'}];
const res = obj.some(e => e.hasOwnProperty("tapCount1"));
console.log(res);
You could get a single object and check the wanted property.
var array = [{ tapCount1: '10' }, { tapCount2: '500' }, { tapCount3: '1250' }, { tapCount4: '1250' }, { wtOfSample: '41.00' }, { initialVolume: '66.0' }, { tapCountvol1: '60.0' }, { tapCountvol2: '53.0' }, { tapCountvol3: '52.0' }, { tapDensity: '0.788' }, { compressibilityIndex: '21.212' }, { hausnerRatio: '1.269' }],
tapCount1 = 'tapCount1' in Object.assign({}, ...array);
console.log(tapCount1);

Array of functions - Javascript

I'm developing a vue-based system, and for my tables, I'm using this: https://github.com/matfish2/vue-tables-2
The component has lots of options. There's the possibility to define custom cell templates to manipulate data before showing them, like this one for the "created_at" column:
templates: {
created_at(h, row) {
return this.formatDate(row.created_at);
},
//(...)
}
I can add other templates as well:
var user_id = function(h,row){return row.id};
...
templates: {
created_at(h, row) {
return this.formatDate(row.created_at);
},
user_id,
(...) // etc
}
But I'd like to group the functions into a variable, so I could reuse the code, like:
var custom_template = [
{ user_id(h,row){return row.id} },
{ user_name(h,row){return row.name} },
{ created_at(h, row){return this.formatDate(row.created_at)} }
];
templates: {
custom_templates
}
EDIT 1:
So i could have something like:
templates: {
user_id(h,row){return row.id} ,
user_name(h,row){return row.name} ,
created_at(h, row){return this.formatDate(row.created_at)}
}
It's not working, but is it possible? Do I need extra code to achieve this?
Thanks! =)
var custom_template = [
function user_id(h, row) {
return row.id;
},
function user_name(h, row) {
return row.name;
},
function created_at(h, row) {
return row.created_at;
}
];
custom_template.forEach(
item => console.log(item(1, {
id: 1,
name: "test",
created_at: new Date()
})));
You need to combine Igor's solution to create array of functions with some form of expanding the array, such as the spread syntax

Categories

Resources