How to split the layer id from url and join with comma - javascript

I have set of array of objects containing url, name and address where I want to get the id from url and join them by a comma.
let arrayOfObjects = [
{ url: 'http://localhost:3000/redApi?id=001&name=abc&address=1234#gmail.com' }
{ url: 'http://localhost:3000/redApi?id=002&name=xyz&address=5647#gmail.com' }
{ url: 'http://localhost:3000/redApi?id=undefined&name=pqr&address=980#gmail.com' }
]
Also if there is "undefined" I want to pass it an empty.
Expected output:
001,002,
Here is my code
let arrayOfObjects = [
{ url: 'http://localhost:3000/redApi?id=001&name=abc&address=1234#gmail.com' }
{ url: 'http://localhost:3000/redApi?id=002&name=xyz&address=5647#gmail.com' }
{ url: 'http://localhost:3000/redApi?id=undefined&name=pqr&address=980#gmail.com' }
]
let urlId = arrayOfObjects.map(x=> x.url)
let getUrl = new URLSearchParams("?" + urlId?.url?.split("?")[1])
let dataId = getUrl.get('id')
console.log(dataId)

First you can map every element of the array to the parameter. You can use URL() to easily get the searchParams from a URL.
let urlIds = arrayOfObjects.map(x => new URL(x.url).searchParams.get('id'));
Now urlIds is an array of the id query string parameters of every URL in the arrayOfObjects array.
Query string parameter values are always strings. There is no such thing as undefined there. If you want to treat "undefined" as empty, you could modify the .map() above, or just use a separate .map() do so. I find the latter to be cleaner.
urlIds = urlIds.map(value => value === "undefined" ? "" : value);
Then finally, if you want them to be joined together separated by a comma, use the .join() method. So the whole code would be:
let arrayOfObjects = [
{ url: 'http://localhost:3000/redApi?id=001&name=abc&address=1234#gmail.com' },
{ url: 'http://localhost:3000/redApi?id=002&name=xyz&address=5647#gmail.com' },
{ url: 'http://localhost:3000/redApi?id=undefined&name=pqr&address=980#gmail.com' }
];
let urlIds = arrayOfObjects.map(x => new URL(x.url).searchParams.get('id'));
urlIds = urlIds.map(value => value === "undefined" ? "" : value);
let joinedUrlIds = urlIds.join(',');
console.log(joinedUrlIds);

You are using URLSearchParams not right take a look at the documentation:
https://medium.com/swlh/urlsearchparams-in-javascript-df524f705317
YOu first need to convert the url to actual URL objects:
let urlId = arrayOfObjects.map(x=> new URL(x.url))
Then you can get the params like so:
urlId.forEach(u => console.log(new URLSearchParams(u).get('id')))
I also noticed you are using a Array as a string when trying to get the id.

Try this:
let arrayOfId = arrayOfObjects.map((obj) => {
let url = obj.url;
let id = url.split("=")[1];
if(id.includes("&")){
id = id.split("&")[0];
}
if (id == "undefined") {
id = "";
}
return id;
});
console.log(arrayOfId);

Here check this out, it works fine.
let arrayOfObjects = [
{url:'http://localhost:3000/redApi?id=001&name=abc&address=1234#gmail.com'},
{url:'http://localhost:3000/redApi?id=002&name=xyz&address=5647#gmail.com'},
{url:'http://localhost:3000/redApi?id=undefined&name=pqr&address=980#gmail.com'}
];
let urlId = arrayOfObjects.map((x)=>{ if ( !isNaN(Number(x.url.slice(x.url.indexOf("?")+4,
x.url.indexOf("?")+5))) )
{ return x.url.slice(x.url.indexOf("?")+4, x.url.indexOf("&")) }
else {return ""}
});
console.log(urlId)
But if you exactly wanted to use URLSearchParams, I can also do it with that

If you prefer a one-liner:
let theIDs = arrayOfObjects
.map(x => new URLSearchParams(x.url.split('?')[1])
.get('id'))
.filter(x => x!=='undefined')
.join(',');

Related

Removing a keyword from a value inside an object - JS

I would like to remove the word ".com" from my object. Currently I can convert the object into a string however my filter is not working.
const items = [
{
company: 'datadog.com'
},
{
company: 'google.com'
},
{
company: 'amazon.com'
},
{
company: 'facebook.com'
}
];
var names = items.map(function(item) {
return item['company'];
});
names.toString();
var filter = names.replace(".com", "");
console.log(filter);
Simply use:
let names = items.map(item => item.company.replace(/[.]com$/, ''));
For each company domain name this returns the domain name with any final '.com' sequence removed.
Using the way you are doing it as a base, you can do something like this.
const items = [...youritems];
var names = items.map(function(item) {
return item['company'];
});
stringNames = JSON.stringify(names)
var filter = stringNames.replace(/.com/g, "");
filteredObject = JSON.parse(filter)
console.log(filteredObject)
But I don't think this is the safest way to go about it, or what you really want (it is not an array of objects). I would do something like this, using es6:
const items = [...youritems];
const newObject = items.map((item) => {
const companyNoCom = item["company"].replace(/.com/g, "")
newItem = {...item, company: companyNoCom}
return newItem
})
console.log(newObject)
This is safer to me, it keeps it an array of objects, and it is cleaner. It uses an arrow function and does not modify the underlying objects.

How to grab only search terms from URL, ignoring multiple delimiters

How can I edit this code to handle multiple delimiters? Currently, it checks for either %7 or |relevance and removes it. But it does not handle multiple delimiters such as in the 2 URL examples below.
https://www.example.com/en-us/search?pq=marketing+agriculture%7Crelevance%7CbestSeller%3Atrue
https://www.example.com/en-us/search?pq=marketing+agriculture|Crelevance|CbestSeller%3Atrue
It should only grab the words: marketing agriculture from the two URLs above.
const params = new URLSearchParams(window.location.search);
if (params.has('pq')) {
const pq = params.get('pq').split('&7').pop().replace('|relevance', '');
console.log(pq);
}
Desired output: To get only the search terms from the URL.
Use Regex:
const params = new URLSearchParams(window.location.search);
const regX = /(\w+[\+]?\w+)/gm;
if (params.has('pq')) {
const pq = params.get('pq').match(regX);
console.log(pq && pq[0]);
}
Here is a way to do it:
let a = "https://www.example.com/en-us/search?pq=marketing+agriculture%7Crelevance%7CbestSeller%3Atrue"
// Converts Params to Object
const parseParams = (querystring) => {
// parse query string
const params = new URLSearchParams(querystring);
const obj = {};
// iterate over all keys
for (const key of params.keys()) {
if (params.getAll(key).length > 1) {
obj[key] = params.getAll(key);
} else {
obj[key] = params.get(key);
}
}
return obj;
};
let aURL = new URL(a) // get the URL instance
let queryObj = parseParams(aURL.search) // grab and parse the parameter string (.search)
let search = queryObj.pq.split('|')[0] // grab the 'pq' prop (i.e that holds the search value.) and split it to get the actual search string
console.log(search)

compare and store string value by array in Javascript / node js

I fetched data from database so its coming in string format and I want to check this string with my array data
my string values come like
fish.jpg
animal.jpg
fish.pdf
animal.pdf
mammal_bio.pdf
fish_bio.jpg
fruit_bio.pdf
I want to compare this data with my array which contain
["mammal_bio.pdf","fruit_bio.pdf","animal_bio.pdf","tree_bio.pdf"]
So i want to compare all the array values which contain _bio.pdf and store them
matchedArray=["mammal_bio.pdf","fruit_bio.pdf"
unmatchedArray=["animal_bio.pdf","tree_bio.pdf"]
Don't use filter but forEach or for loop instead because you don't need to loop through all items again to get the two arrays.
const input = `fish.jpg
animal.jpg
fish.pdf
animal.pdf
mammal_bio.pdf
animal_bio.pdf
fish_bio.jpg
tree_bio.pdf
fruit_bio.pdf`;
check = ["mammal_bio.pdf", "fruit_bio.pdf", "animal_bio.pdf", "tree_bio.pdf"];
const matched = [];
const unmatched = [];
input
.split("\n")
.forEach(item =>
check.slice(0, 2).includes(item)
? matched.push(item)
: check.slice(-2).includes(item)
? unmatched.push(item)
: null
);
console.log({ matched });
console.log({ unmatched });
First you can filter out the strings which endsWith _bio.pdf.
Then for matched result filter with fiterArr and similarly for unmatched result
let filterArr = ['mammal_bio.pdf','fruit_bio.pdf'];
let bioArr = arr.filter(a => a.endsWith('_bio.pdf'));
let matched = bioArr.filter(b => filterArr.includes(b));
let unmatched = bioArr.filter(b => !filterArr.includes(b));
Just use
Array.filter
method.
If you return true the item will be inside the new Array, false excludes the item.
const noBioList = []
const bioList = list.filter(item => {
if (item.includes('_bio.pdf') {
return true
} else {
noBioList.push(item)
return false
}
}
console.log(bioList)
console.log(noBioList)
const input = `fish.jpg
animal.jpg
fish.pdf
animal.pdf
mammal_bio.pdf
animal_bio.pdf
fish_bio.jpg
tree_bio.pdf
fruit_bio.pdf`;
const inputList = input.split(/\n\s*/g)
const check = ["mammal_bio.pdf", "fruit_bio.pdf"];
const { matched, unmatched } = inputList.reduce((result, file) => {
if(/_bio\.pdf/.match(file)) {
if(check.indexOf(file) < 0) result.unmatched.push(file);
else result.matched.push(file)
}
return result
}, {
matched: [],
unmatched: []
})

How to return ONLY the matched / filtered string in an array?

I'm creating a small application for connection to an API and append cards from magic the gathering JSON file onto an HTML webpage.
Those cards should be searchable and for that to happen I need to somehow create a filter()
I'm new and still in school at this subject.
I have pulled out only the card Names in the variable called "arr" and is trying to filter out / or match with a value from the search input field which is "strInput"
document.getElementById("searchButton").addEventListener("click", function(e){
const parentDiv = document.getElementById("cards");
if ( parentDiv.hasChildNodes() === true ) {
removeStuff();
} else {
filteredCards("https://api.magicthegathering.io/v1/cards");
}
}, false)
displayCards("https://api.magicthegathering.io/v1/cards");
function filteredCards(url) {
fetch(url)
.then((resp) => resp.json())
.then((data) => {
let myInput = document.getElementById("search").value;
let strInput = '"' + myInput + '"';
let arr = [];
for ( i in data.cards) {
let jsonValue = data.cards[i];
let name = jsonValue.name;
arr.push(name);
}
let result = strInput.match(arr);
console.log(result);
console.log(arr);
console.log(strInput);
});
};
console.log(arr); // returns NULL even thought the string matches.
There's two ways to do it simply that I could think of, .find() and .filter()
.find() is going to return you the first match, and as a string
.filter() is going to return you the all matches, and as an array
They both work with the same style of code, you're just changing the method name
arr.filter(item => item === strInput) | arr.find(item => item === strInput
Just as a little aside, there's a few things you could swap out to get those sweet sweet brownie points
let arr = [];
for ( i in data.cards) {
let jsonValue = data.cards[i];
let name = jsonValue.name;
arr.push(name);
}
Can instead be wrote using the map function
let arr = data.cards.map((card) => card.name);
.
Also, you don't need to do '"' + myInput + '"'; to make sure something is a string, which is what you might be trying to do there - you can just use myInput.toString() - of course your data might have the names include the quotes, but just in case this is a mistake I thought I'd point it out
The parameter passed to match method is not really a matcher but a string. The method expects a regex to be passed in.
Just build out a simple regex expression and then iterate over the data.cards and add it into the array if the condition passes. You can look at the filter available on the array object.
let myInput = document.getElementById("search").value;
let myInputRegex = new Regex(myInput, 'gi');
let arr = [];
const matchedTokens = data.cards.filter(card => {
return card.name.match(myInputRegex);
});
console.log(matchedTokens);
console.log(strInput);
You can make a method that uses array.Find() and pass in the arr and strInput. array.Find() will find the first match
getName: function (arr, strInput) {
var name = arr.find(n => n === strInput)
return name
}
Here's some more reading from the official mozzila docs
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find
Thanks!
This was exactly what i was looking for :D
let myInput = document.getElementById("search").value;
let myInputRegex = new Regex(myInput, 'gi');
let arr = [];
const matchedTokens = data.cards.filter(card => {
return card.name.match(myInputRegex);
});
console.log(matchedTokens);
console.log(strInput);

Issue in removing object using Lodash _remove

I am having an Object:
ids = [ "-LIof_e0hPtXKtkc4Uh9", "-LIjBcGO7m7VQ-B3pfYt" ]
If I Iterate using .map function of lodash
_.map(ids, (userID, key) => {
console.log('Lopping userId',userID);
})
it gives me value of each id.
Now when I am trying to remove it using _remove it is not working as expected.
_.remove(ids, (value, key, obj) => value == idToBeRemoved);
Still there is no difference in ids Object.
I am really new to angular4 and using lodash for the first time.
I just wanted to remove a value from ids object and get the remaining object.
Print of console.
I am using firebase and trying to delete data after retrieving it from firebase :
deleteTransactWith(transactWithKey,transactWithUser) {
let currentUser = this._authService.getLoggedInUser();
console.log(transactWithUser.groups)
console.log(Object.keys(transactWithUser.groups).length)
console.log('key To remove',transactWithKey)
for (var key in transactWithUser.groups) {
if (transactWithUser.groups.hasOwnProperty(key)) {
let group = this.firebase.object(`/url/${currentUser.$key}/${key}`);
group.snapshotChanges().take(1).subscribe((groupData: any) => {
groupData = groupData.payload.toJSON();
//console.log('not removed',groupData.userIds)
console.log('key',transactWithKey)
_.remove(groupData.userIds, (value) => value == transactWithKey);
//_.pull(groupData.userIds, transactWithKey);
console.log('removed',groupData.userIds)
});
}
}
You want _filter instead
const ids = [ "-LIof_e0hPtXKtkc4Uh9", "-LIjBcGO7m7VQ-B3pfYt" ]
const idToBeRemoved = "-LIof_e0hPtXKtkc4Uh9"
const filteredIds = _.filter(ids, function(id) { return id !== idToBeRemoved})
console.log(filteredIds)
You can simply use lodash _.pull
const _ = require("lodash");
const ids = [ "-LIof_e0hPtXKtkc4Uh9", "-LIjBcGO7m7VQ-B3pfYt" ]
const result = _.pull(ids, "-LIjBcGO7m7VQ-B3pfYt" )
console.log(filteredIds)
First find the index of what you are removed item and next pull out from it by _.pullAt(lodash)
let getIndex= _.findIndex(this.images, function(o) { return o.name == img.name; });
let removedImage = _.pullAt(this.images, getIndex) ;

Categories

Resources