replace url params with values of an object - javascript

I have a object like this:
let data = {
url: "https://test.ir/apps/:type/:id/",
params: {
id: "com.farsitel.bazaar",
type: "xyz",
},
query: {
ref: "direct",
l: "en",
},
};
I want to replace :type and :id in url with equivalent key to each from params object. what is the best solution in javascript?

Solution based on matching keys from params to the value of a regular expression from key url, followed by an update of that key.
On input: https://test.ir/apps/:type/:id/
On output: https://test.ir/apps/xyz/com.farsitel.bazaar/
let data = {
url: "https://test.ir/apps/:type/:id/",
params: {
id: "com.farsitel.bazaar",
type: "xyz",
},
query: {
ref: "direct",
l: "en",
},
};
let new_url = data.url.replace(/:(\w+)/g, (match, key) => data.params[key] || match);
data.url = new_url;
console.log(data);

Could you just use String.replace?
const data = {
url: "https://test.ir/apps/:type/:id/",
params: {
id: "com.farsitel.bazaar",
type: "xyz",
},
query: {
ref: "direct",
l: "en",
},
}
const url = data.url.replace(":type", data.params.type).replace(":id", data.params.id);
console.log(url)

Related

How to $match a field conditionally in mongo DB

I have the following schema:
User: {
...otherFields,
isDumb: false,
type: "A" // could be "A", "B", or "C"
}
I want to fetch all dumb users by default and fetch by type only if the type is passed through the parameters.
static async getUsers(req: any, res: Response) {
const { type = "" } = req.params;
const queryPipeline = [
{
$match: {
isDumb: true,
type: // I want to only filter by type if the param is passed in
}
}
]
const users = await User.aggregate(queryPipeline);
So if my data was:
[
{
...otherFields,
isDumb: false,
type: "A"
},
{
...otherFields,
isDumb: true,
type: "B"
},
{
...otherFields,
isDumb: true,
type: "C"
}
]
and req.params.type was "B", I should get back:
[
{
...otherFields,
isDumb: true,
type: "B"
}
],
if req.params.type was undefined, I should get all dumb users
[
{
...otherFields,
isDumb: true,
type: "B"
},
{
...otherFields,
isDumb: true,
type: "C"
}
]
you just have to build an object and pass it to match
const matchParams = req.params.type ? {isDumb:true,type:req.params.type } : {isDumb:true }
You can create the object using JS:
const params = "A" // get req.params as you want
let query = {$match:{isDumb:true}}
if(params) query.$match.type = params
console.log(query)
First, you don't need to use Aggregation Framework for simple find query. You can use find method instead.
Second, consider approach where you initialize the filter with isDumb: true, and add new type property only if req.params.type exists.
let filter = { isDumb: true };
if(req.params.type) filter.type = req.params.type;
const users = await User.find(filter);

Search object within object and get the key

I have an object router shown below. lets say I have another var x = "/podcast" and I want to find which key this variable x would reside. For example in this case I want to return the value "M2"
How can I search this object router and it's sub-objects to return the appropriate key?
Thanks!
var router = {
M1: {
url: "/",
description: "",
title: "",
image: "",
},
M2: {
url: "/podcast",
description: "",
title: "",
image: "",
},
M3: {
url: "/about",
description: "",
title: "",
image: "",
},
};
You can use Object.keys() to get Array of object keys then .filter(), here is a working snippet:
const search = '/podcast';
const router = {
M1: {
url: "/",
description: "",
title: "",
image: ""
},
M2: {
url: "/podcast",
description: "",
title: "",
image: ""
},
M3: {
url: "/about",
description: "",
title: "",
image: ""
}
};
const foundElement = Object.keys(router).filter((el) => router[el].url === search);
console.log(foundElement[0]);
To get your keys you use Object.keys(object)
To search the key you can use filter() or find().
To apply the condition you define callback function inside filteror find.
In my case, I used find function :
const foundElement = (router, searchableValue) => {
const founded = Object.keys(router).find(
(value) => router[value].url === searchableValue
);
return founded === undefined ? "Key not found" : founded;
};
const searchableValue = "/podcast";
console.log(foundElement(router, searchableValue));

React - Loop through multiple nested arrays json object response then update State

I have some data that has the following shape. The schedule data also has other identifying information attached to it, being schedules.included which is an array of arrays. I want to loop through each included array and find it by type element. I'm not entirely sure how to get each included[] by type then update state with data from each array, respectively. Is forEach the correct approach?
const schedules = {
data: [
{
id: "2147483610",
type: "Schedule"
}
],
included: [
{
id: "21468486",
type: "Query",
name: "Query1"
},
{
id: "43573457345",
type: "DataSource",
name: "DataSource1"
}
]
};
I then want to update state with whatever data I need.
getData = () => {
axios({
method: "get",
url: `/endpoint/with/this/data`
})
.then(response => {
console.log(response);
var obj = schedules.included[i].type;
obj.forEach(function(type) {
alert(type.name);
});
this.setState({
schedules: schedules.data,
//update with name from type Query
});
})
.catch(error => console.log(error.response));
};
If you want to find the name of the element from the included array which has type = Query, and there is only one such element:
var query = schedules.included.find(el => el.type == "Query");
console.log(query.name); // output Query1
If there is more than one query element you could use filter to get all query elements, then loop thru them doing stuff with each one.
var queries = schedules.included.filter(el => el.type == "Query");
queries.forEach(q => console.log(q.name));
If there is only one element with the type you are looking for then you can use find or if there is more use filter.
const schedules = {
data: [
{
id: "2147483610",
type: "Schedule"
}
],
included: [
{
id: "21468486",
type: "Query",
name: "Query1"
},
{
id: "43573457345",
type: "DataSource",
name: "DataSource1"
}
]
};
const typeMatched = schedules.included.find( included => included.type === "Query");
console.log(': ', typeMatched);
const schedulesObj = {
data: [
{
id: "2147483610",
type: "Schedule"
}
],
included: [
{
id: "21468486",
type: "Query",
name: "Query1"
},
{
id: "43573457345",
type: "DataSource",
name: "DataSource1"
},
{
id: "21468482",
type: "Query",
name: "Query2"
},
{
id: "21468484",
type: "Query",
name: "Query3"
},
]
};
const typeMatchedArray = schedulesObj.included.filter( included => included.type === "Query");
console.log('Query Type List: ', typeMatchedArray)

How to map properties of an object to another?

I know there are many questions on this matter, but I can't figure out how to apply it in my case.
Code is as following:
const mailDocumentSchema = new schema.Entity('mailDocuments', {}, { idAttribute: 'identifier' });
const mailSchema = new schema.Entity('mails', { emailDocument: [mailDocumentSchema] }, { idAttribute: 'identifier' });
const mailAccountSchema = new schema.Entity('mailAccounts', { mails: [mailSchema] }, { idAttribute: 'address' });
const mailMapper = (item: any): Mail => ({
id: item.identifier,
title: item.subject,
documents: item.emailDocument,
subject: item.realSubject,
receiver: item.receiver,
createdDate: item.createdDate,
sendDate: item.sendDate,
body: item.body
});
const mailDocumentMapper = (item: any): MailDocument => ({
id: item.identifier,
docId: item.oldDocId,
name: item.name,
createdDate: item.createdDate,
bodyStatus: item.bodyStatus
});
export const undefinedDocumentsMapper = (response: any[]): NormalizedMailbox => {
const undefinedDocuments = map(groupBy(response, item => item.receiver), (item, key) => ({ name: null, address: key, mails: item }));
const normalizedResponse = normalize(undefinedDocuments, [mailAccountSchema]);
return {
mailAccounts: Object.values<MailAccount>(normalizedResponse.entities.mailAccounts),
mails: Object.values<any>(normalizedResponse.entities.mails).map(mailMapper),
mailDocuments: Object.values<any>(normalizedResponse.entities.mailDocuments).map(mailDocumentMapper)
};
};
API response is:
[
{ identifier: "...", title: "...", receiver: "...", emailDocuments: [{...}] },
...
]
What I want is to map the receiver and title properties from mails entity objects to mailDocuments entity objects.
As a result to get mailDocuments entity objects as such:
{
id: "...",
docId: "...",
name: "...",
createdDate: "...",
bodyStatus: ...,
title: "...",
receiver: "..."
}
How to accomplish this?
If I understand correctly, you can do the following:
mails.forEach(mail => {
mail.documents.forEach(document => {
document.receiver = email.receiver
document.title = email.title
})
})

Declaring dynamic keys in json (javascript, node)

I have an array of objects, each object is similar to:
{ word: 'intentional',
definition: 'done by intention or design',
type: 'adjective',
Synonyms: [ 'conscious', 'deliberate', 'intended', 'knowing', ] }
I am trying to convert the whole array into following json format:
{
"conscious": {
"data": ["done by intention or design"],
"type": "adjective",
"Synonym For": ["intentional"]
},
"deliberate": {
"data": ["done by intention or design"],
"type": "adjective",
"Synonym For": ["intentional"]
},
...
}
This json format is an input to another program, which I do not control.
I am running it on node.js.
How can I declare an object and then loop through the array to fill it as intended?
var obj = { word: 'intentional',
definition: 'done by intention or design',
type: 'adjective',
Synonyms: [ 'conscious', 'deliberate', 'intended', 'knowing' ] },
res = obj.Synonyms.reduce(function(s,a) {
s[a] = { data: [obj.definition], type: obj.type, SynonymFor: [obj.word] };
return s;
}, {});
console.log(res);
var jsonObj = {};
wordArray.forEach((word) => {
word.Synonyms.forEach((synonym) => {
jsonObj[synonym] = {
data: [word.definition],
type: word.type,
'Synonym For': [word.word]
};
})
})

Categories

Resources