I want to retrieve values form url parameters, but the parameters are not constant: it can be "referer=" or "utm_source=" or "source=".
I can get the value with
url.searchParams.get("referer");
Complete script for now :
function() {
var url_string = window.location.href;
var url = new URL(url_string);
var ref = url.searchParams.get("referer");
if (ref == undefined) {
return "No Referer";
} else {
return ref;
}
}
Can I include some regex like:
var ref = url.searchParams.get.match(/referer|source|utm\_source/g);
Can I include some regex
No. That isn't a feature of get.
You can use a set of ||s:
var ref = url.searchParams.get("referer") || url.searchParams.get("source") || url.searchParams.get("utm_source");
Or take an array of key names, map them to the values in the URL, filter out any which don't have a value, then take the first (and presumably only) value off the array.
var possible_key_names = ["referer", "source", "utm_source"];
var ref = possible_key_names
.map(name => url.searchParams.get(name))
.filter(value => !!value)
.shift();
You can loop over the searchParams like so:
var url = new URL("https://example.com/page?referer=&utm_source=google");
var value;
for (var [key, val] of url.searchParams) {
if (key.match(/^(referer|source|utm_source)$/) && val !== "") {
value = val;
break;
}
}
console.log(value);
Related
I have json object with a key named favorite, it has a value of true, when the button is pressed I want to overwrite the value of the favorite key to false and vica versa.
This is what`s inside the json object:
allPlaces: "[{"title":"Test1 ","description":"Test 2","category":"restaurant","favourite":false}]"
function favourite(element) {
var allPlaces = JSON.parse(localStorage.getItem("allPlaces"));
var placeIndex = element.getAttribute("data");
places = {allPlaces}
if (allPlaces["favourite"] == true) {
places.favourite[placeIndex] = false;
element.querySelector('ion-icon').setAttribute('name', 'star-outline');
} else {
console.log("working");
places.favourite[placeIndex] = true;
element.style.color = '#FFE234';
element.querySelector('ion-icon').setAttribute('name', 'star');
}
localStorage.setItem("allPlaces", JSON.stringify(places));
}
allPlaces is an array (in this case it has 1 item) so therefore in order to change the property of an object inside it you have to give it an index like so allPlaces[0].favorite = true
I added some code as a reference
const allPlaces = '[{"title":"Test1 ","description":"Test 2","category":"restaurant","favourite":false}]';
const places = JSON.parse(allPlaces);
places[0].favorite = true;
console.log(places[0]);
This is the code below, I am confused about this line.
What is this code doing? where does this title ( === title) comes from.
Plz, can anybody explain me about this?
var duplicateNote = notes.filter((note) => note.title === title);
var addNote = (title, body) => {
var notes = [];
var note = {
title,
body
}
try {
var notesstring = fs.readFileSync('notes-data.json');
notes = JSON.parse(notesstring);
} catch (e) {
}
console.log(Array.isArray(notes));
var duplicateNote = notes.filter((note) => note.title === title);
the filter function allow you to create a new array after filtering vaues of an old one
var duplicateNote = notes.filter((note) => note.title === title);
create an array duplicateNote containing entries of note where the entry's title is strictly equal to the title passed when calling the function.
It is equivalent to :
var duplicateNote = []
for (let note of notes) {
if (note.title === title) {
duplicateNote.push(note)
}
}
I am passing json and a key to below function to retrieve its value. The key can be like abc.cde.def nad it can also be like fgh only.
If the keys contain . then it is a nested json and values has to be retrieved accordingly which is happening correctly but if it is a plain json having no nest then it is not working. Printing the length of keysData (in case the key is like fgh) it prints 3 where it should print 1.
function getValueFromJson(jsonInput,keyInput) {
if(keyInput.includes('.')){
var keysData = keyInput.split('.');
}
else {
keysData = keyInput.toString()
}
var jsonHierarchy = jsonInput;
if(parseInt(keysData.length) === parseInt('1')){
console.log(jsonHierarchy)
console.log(keysData )
console.log(jsonHierarchy[keysData ])
jsonHierarchy = jsonHierarchy[keysData ];
}
return jsonHierarchy;
};
Can anyone please help how can I handle this ?
you dont need to check for if(keyInput.includes('.'))
just do keyInput.split('.')
//for Ex.
'abc.defg'.split('.') // result ['abc', 'defg']
'abc'.split('.') // result ['abc']
and also
if(parseInt(keysData.length) === parseInt('1'))
//can be used as
if(keysData.length === 1)
and your complete function should be
function getValueFromJson(jsonInput,keyInput) {
var keysData = keyInput.split('.');
var jsonHierarchy = jsonInput;
keysData.forEach(function(d) {
if(jsonHierarchy)
jsonHierarchy = jsonHierarchy[d];
})
return jsonHierarchy;
};
var jsonData = {
'abc': {
'def': {
'gh': 'value1'
},
'xyz': 'value2'
}
};
function getValueFromJson(jsonInput, keyInput) {
var keysData = keyInput.split('.');
var jsonHierarchy = jsonInput;
keysData.forEach(function(d) {
if (jsonHierarchy)
jsonHierarchy = jsonHierarchy[d];
})
return jsonHierarchy;
};
function get() {
var val = document.getElementById('key').value;
if (val)
console.log(getValueFromJson(jsonData, val));
};
<input id="key" />
<button onclick="get()">Get Value</button>
Convert your string to an array, then your length with show properly.
var keysData = keyInput.split('.')
I need to convert values from one Array variable into fields of another variable in Javascript.
My variable is
field = ["entries", "body"]
and it needs to become something like
req.body.entries.body
I tried doing something like
field.forEach(function(prop){
req.body[prop] = "...";
}
but that works only on req.body.entries and req.body.body. And I need it to go all the way to req.body.entries.body
I'm doing this to get the data from a form in a document field (named entries[body]), do some cleaning up on that data, and then pass it back to node.js as if it was the request that was originally made.
UPDATE
All I need to do is to basically
exports.sanitize = function(field){
// field = ["entry","body"];
return function(req, res, next){
val = getField(req, field); // val = "Some string with data"
val = some_process(val); // some_process is a function that cleans up the string
req.body.entry.body = val; // HOW TO TAKE entry.body from the field array???
next();
}
};
As you can see, all I want is to NOT hard code entry.body but take it from field array values that passes the name of the field for processing.
If you can think of a more elegant solution to do this, please, let me know.
Thanks!
This works:
var fields = [ "field1", "field2", "field3", "field4" ];
var obj = req.body;
fields.forEach(function(prop) {
obj[prop] = {};
obj = obj[prop];
});
You want
var obj = req.body;
for (var i=0; i<fields.length-1; i++)
obj = obj[fields[i]];
var prop = fields[i];
obj[prop] = cleanUp(obj[prop]);
This will work only if req.body.entries.body is already defined:
field = ["entries","body"];
var toeval="req.body";
field.forEach(function(prop){
toeval+="."+prop;
});
toeval+="=\"...\"";
eval(toeval);
I was able to accomplish this using recursion. Hope this helps!
var foo = {
bar: {}
};
var fields = ['foobar', 'barfoo'];
function setVar (currentVar, arr, counter) {
if (arr[counter] === undefined) {
return;
}
currentVar[arr[counter]] = {};
setVar(currentVar[arr[counter]], arr, counter + 1);
}
setVar(foo.bar, fields, 0);
Why does my array length always come out to 0 even though var email is equal to a string. (I've alerted out var email and the data is there).
var emails = new Array();
//get all the emails
$('.emailBox input').each(function (i)
{
var email = $(this).val();
if(email != '')
{
emails[email] = email;
alert(emails.length);
}
});
Because you're adding a property to the array.
var a = [];
a.foo = 42;
a.length === 0; // true
Instead try
emails.push(email);
This is the same as emails[emails.length] = email
As an aside:
var emails = new Array();
Is bad. You should be using [] instead of new Array() mainly because it's more terse and readable.
if (email != '') {
The above can be replace with if (email) { in case jQuery ever returns undefined or null
To make the entire code more elegant you should use
var emails = $('.emailBox input').map(function() {
return this.value;
}).filter(function (k, v) { return v; }).get();
Or without jQuery
var emails = [].map.call(document.querySelectorAll(".emailBox input"), function (v) {
return v.value;
}).filter(function (v) { return v; });
Although you'll need a QSA shim and a ES5 shim for legacy platform support.
Edit:
If you want the array to be unique then reduce it.
var arr = arr.reduce(function (memo, val, key, arr) {
// if the first index of the value is the index then add it.
// if the first index is different then we already have it.
if (arr.indexOf(val) === key) {
memo.push(val);
}
return memo;
}, []);
You could do all of that using a few jQuery methods.
var emails = $('.emailBox input')
.map(function() { return $(this).val() || null; })
.get();
jsFiddle.
emails[email] = email isn't doing what you want it to do. Try
emails.push(email);