Manipulate CQL params from database in javascript - javascript

I store CQL filtering params as varchar in the database which i have to manipulate in JavaScript. street_desc is a variable in javascript. How can i assign it to the string dynamically?
Whatever is inside the input_params has to replace the cql_param string
var street_desc= "whatever"; //input from the user
var town_code = "whatever2"; //input from the user
var cql_param= "roadname_gr='street_desc'&towndesc is not null&town_code='town_code'"; //comes from database
var input_params = [street_desc,town_code]; //declare input params to replace the cql string
The output should be:
"roadname_gr='whatever'&towndesc is not null&town_code='whatever2'";
What i have tried...
var street_desc = "whatever"; //input from the user
var town_code = "whatever2"; //input from the user
var cql_param = "roadname_gr='street_desc'&towndesc is not null&town_code='town_code'"; //comes from database
var input_params = {
street_desc: street_desc,
town_code: town_code
}; //declare input params to replace the cql string
for (const [key, value] of Object.entries(input_params)) {
console.log(`${key}: ${value}`);
cql_param.replace(key, value);
}

I update my answer to use a reducer
let cql_param= "roadname_gr='street_desc'&towndesc is not null&town_code=1";
var street_desc= "whatever"; //input from the user
var town_code = "whatever2"; //input from the user
var input_params = [street_desc,town_code];
var input_params_names = ["street_desc","1"];
let i =0;
const result = input_params.reduce((ac,c)=>{
return ac.replace(input_params_names[i++], c);
},cql_param)
console.log(result)

I managed to solve it. Here is what i did:
Declare an object with my input params i want to replace. Iterate over the key-value pairs and replace the string.
var street_desc_inp = "whatever"; //input from the user
var town_code_inp = "whatever2"; //input from the user
var cql_param = "roadname_gr='street_desc_inp'&towndesc is not null&town_code='town_code_inp'"; //comes from database
console.log(cql_param)
var input_params = { //declare input params to replace the cql string
street_desc_inp: street_desc_inp,
town_code_inp: town_code_inp
};
for (const [key, value] of Object.entries(input_params))
cql_param = cql_param.replace(key, value);
console.log(cql_param)

Related

JSON 2D key value Response Text into Drop Down

I'm getting Response string same as like this.
var txtResponse = "{"Tom":{"Given Name":"Tom","Employee Number":"21"},"Sam":{"Given Name":"Sam","Employee Number":"23"},"Jack":{"Given Name":"Jack","Employee Number":"19"}}";
Need to put this on html drop down and assign Text as 'Given Name' and value as 'Employee Number' of each employee by java script.
I have used this to assign values to drop down for other array.
var select = document.getElementById("selectelement");
var optionContent = document.createElement("option");
optionContent.textContent = "";
optionContent.value = "";
select.appendChild(optionContent);
can you please help me to assign 'textContent' and 'value' from above response through loop.
You can iterate through all the keys in the json object like the following,
var txtResponse = '{"Tom":{"Given Name":"Tom","Employee Number":"21"},"Sam":{"Given Name":"Sam","Employee Number":"23"},"Jack":{"Given Name":"Jack","Employee Number":"19"}}';
var jsonResponse = JSON.parse(txtResponse);
var select = document.getElementById("selectelement");
Object.keys(jsonResponse).forEach(key => {
var optionContent = document.createElement("option");
optionContent.textContent = jsonResponse[key]['Given Name'];
optionContent.value = jsonResponse[key]['Employee Number'];
select.appendChild(optionContent);
})
let res:any='{"Tom":{"Given Name":"Tom","Employee Number":"21"},"Sam":{"Given Name":"Sam","Employee Number":"23"},"Jack":{"Given Name":"Jack","Employee Number":"19"}}';
this.res=JSON.parse(this.res);
console.log('res==',this.res)
let select=document.getElementById("selectelement");
for(let el in this.res){
let optionContent=document.createElement("option");
optionContent.innerHTML=this.res[el]['Given Name'];
optionContent.value=this.res[el]['Employee Number'];
select.appendChild(optionContent);
}
<select id="selectelement"> </select>

Concatenate JSON and Index variables

There is an input field, Which has name metadata.country. The functionality is to get the name and split than make those index in square brackets ['metadata']['country']. I want to concatenate JSON and Index variables to get the country.The issue is when I try to join, it return [object Object].
Code:
//Input Fields (Html)
<input id="dataX" name="metadata.country">
<input id="dataY" name="metadata.city">
//Get ID
var inputField_Name = document.getElementById("dataX").attr['name'];
//JSON Data
var json = {name:"John",metadata:{country:"USA",city:"newyork"}};
//Split by dot
var targetName = inputField_Name.split('.');
//Convert them into square brackets
let copy='';
targetName.map(function(key, index) {
copy +="['"+key+"']";
});
//Response copy: ['metadata']['country']
console.log(json + copy);
//Response: [object Object]['metadata']['country']
Expected Response:
"USA"
//Don't want this method:
json [1];
Below snippet will help you find out the data from the object. Hope this helps
var inputField_Name = "metadata.country"
var json = {name:"John",metadata:{country:"USA"}};
var targetName = inputField_Name.split('.');
let copy='';
const data = targetName.reduce((result, targetKey) => result[targetKey] || {}, json)
console.log(data)
Below method can be used to update the value at the specified location without mutating the original object. you can get the data from the method and can use it to do setState.
let updateValue = (dataObj, keys, updatedValue) => {
let json = JSON.parse(JSON.stringify(dataObj));
let result = (keys ||[]).reduce((result, targetKey, index) => {
if(index === targetName.length - 1){
result[targetKey] = updatedValue;
return result[targetKey]
}
return result[targetKey] || {}
}, json)
return json;
}
var inputField_Name = "metadata.country"
var json = {name:"John",metadata:{country:"USA"}};
var targetName = inputField_Name.split('.');
const updatedJsonObj = updateValue(json, targetName, "CANADA")
console.group("Updated JSON");
console.log(updatedJsonObj)
console.groupEnd()
console.group("Original JSON");
console.log(json)
console.groupEnd()
You can try
JSON.stringify(json) + JSON.stringify(index)
var json = {name:"John",country:"USA"};
var index= ['1'];
console.log(JSON.stringify(json) + JSON.stringify(index));
You don't need to map through you can directly get the value from the object.
let inputField_Name = "metadata.country"
let json = {name:"John",metadata:{country:"USA"}};
let [meta, key] = inputField_Name.split('.');
let out= json[meta][key];
console.log(out)

php update localstorage array without adding new array

I add an array localstorage. works fine. I can also retrieve it . how can I.update where ID is something without adding a new array.
example ..
how can I go update surname and age where ID = sam without creating new array
var objItem = {};
if (localstorage.getItem("records") == null) {
objArr = [];
} else {
objArr = JSON.parse(localstorage.getItem("records"));
}
var ID = "sam";
var surname = "edward";
var age = "two";
objItem.ID = ID;
objItem.surname = surname;
objItem.age = age;
objArr.push(objItem);
localstorage.setItem("records", JSON.stringify(objArr));
localStorage is just a key-value store. To update, you just save to the same key. That is, you retrieve your array, parse, update, stringify then save to the same key.
To find the item on the array, you can use array.filter and create an array containing only the values that match the ID. Update the values inside that array and save the original array.
let names = [...names...];
let matches = names.filter(person => person.ID === ID);
matches.forEach(person => person.surname = surname);
let toSave = JSON.stringify(names);
// save to localstorage

get Input values dynamically in jquery

I am devolping a web application using symfony framework. I have aproblem in forms. Here is my code:
$('#bookCleaningForm').submit(function() {
// get the array of all the inputs
var $inputs = $('#bookCleaningForm :input[type=text]');
// get an associative array of the values
var values = {};
var allVAlues='';
$inputs.each(function() {
values[this.name] = $(this).val();
allVAlues = values[this.name];
});
alert(allValues);//console.log(allValues);
saveBoookCleaning(allVAlues);
});
In the loop i got all data in allValues variable.But when I access outside the loop i got only one value.
Please help
Each time in the each loop you are assigning the variable allValues to the value of the current input. If you want to store the values as an array you could do this:
$('#bookCleaningForm').submit(function() {
// get the array of all the inputs
var $inputs = $('#bookCleaningForm :input[type=text]');
// get an associative array of the values
var values = {};
var allVAlues=[];
$inputs.each(function() {
values[this.name] = $(this).val();
allVAlues.push(values[this.name]);
});
alert(allVAlues);//console.log(allValues);
saveBoookCleaning(allVAlues);
});
Or, if you want them as a string:
$('#bookCleaningForm').submit(function() {
// get the array of all the inputs
var $inputs = $('#bookCleaningForm :input[type=text]');
// get an associative array of the values
var values = {};
var allVAlues='';
$inputs.each(function() {
values[this.name] = $(this).val();
allVAlues += values[this.name];
});
alert(allVAlues);//console.log(allValues);
saveBoookCleaning(allVAlues);
});

user input to URL

I have some url and I need to replace some parts of it with user input from input type="text" and move to new link with button click.
How can I place variables in URL ?
//some-url/trends.cgi?createimage&t1=1412757517&t2=1412843917&assumeinitialstates=yes&assumestatesduringnotrunning=yes&initialassumedhoststate=0&initialassumedservicestate=0&assumestateretention=yes&includesoftstates=no&host=SCP-3&service=MODIFICATION+TIME+EDR+FILES&backtrack=4&zoom=4
i have function, but it place input at the end of url.
function redirect() {
var baseUrl = 'http://google.com.ua/';
document.myform.action=baseUrl + document.getElementById('url').value;
}
<form name="myform" method="post" onsubmit="redirect()">
<input type="text" id="url">
<input type="submit" value="submit">
</form>
You could build out manual query string parsers and constructors, an example would be like:
function parseQuery(qstr){
var query = {};
var a = qstr.split('&'); //take the passed query string and split it on &, creating an array of each value
for (var i in a) { //iterate the array of values
var b = a[i].split('='); //separate the key and value pair
query[decodeURIComponent(b[0])] = decodeURIComponent(b[1]); //call decodeURIComponent to sanitize the query string
}
return query; //returned the parsed query string object
}
function buildQuery(obj){
var str = [];
for(var p in obj) //iterate the query object
if (obj.hasOwnProperty(p)) { //check if the object has the propery name we're iterating
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p])); //push the encoded key value pair from the object into the string array
}
return str.join("&"); //take the array of key value pairs and join them on &
}
Then below we take the string that you gave, for example:
var $str = 'createimage&t1=1412757517&t2=1412843917&assumeinitialstates=yes&assumestatesduringnotrunning=yes&initialassumedhoststate=0&initialassumedservicestate=0&assumestateretention=yes&includesoftstates=no&host=SCP-3&service=MODIFICATION+TIME+EDR+FILES&backtrack=4&zoom=4';
Now we call the parseQuery function on our string.
var obj = parseQuery($str);
Then we iterate the object which was produced from our parseQuery function
Object.keys(obj).forEach(function(k, i) {
switch(k){
case 't1':
obj[k] = 'replacedt1';
break;
case 'service':
obj[k] = 'replacedServices';
break;
case 'host':
obj[k] = 'replacedHost';
}
});
Now the obj variable has the newly updated values. We can rebuild the query using our buildQuery function by passing the object in.
console.log(buildQuery(obj));
Which will produce something like:
createimage=undefined&t1=replacedt1&t2=1412843917&assumeinitialstates=yes&assumestatesduringnotrunning=yes&initialassumedhoststate=0&initialassumedservicestate=0&assumestateretention=yes&includesoftstates=no&host=replacedHost&service=replacedServices&backtrack=4&zoom=4
As usual, the jsFiddle
You can use the new URL object (for older browsers, there is a polyfill) :
var url = new URL("http://some-url/trends.cgi?createimage&t1=1412757517&t2=1412843917&assumeinitialstates=yes&assumestatesduringnotrunning=yes&initialassumedhoststate=0&initialassumedservicestate=0&assumestateretention=yes&includesoftstates=no&host=SCP-3&service=MODIFICATION+TIME+EDR+FILES&backtrack=4&zoom=4");
url.searchParams.set("t1", "someNewT1");
url.searchParams.set("t2", "someNewT2");
url.searchParams.set("host", "someNewHost");
url.searchParams.set("service", "someNewService");
alert(url.href);
/*
http://some-url/trends.cgi?host=someNewHost&assumestateretention=yes&initialassumedservicestate=0&t2=someNewT2&initialassumedhoststate=0&assumeinitialstates=yes&zoom=4&backtrack=4&createimage=&assumestatesduringnotrunning=yes&includesoftstates=no&service=someNewService&t1=someNewT1
*/
Played with JavaScript a bit, I believe this solves your problem: http://jsfiddle.net/dk48vwz7/
var linktext = "http://site/some-url/trends.cgi?createimage&t1=1412757517&t2=1412843917&assumeinitialstates=yes&assumestatesduringnotrunning=yes&initialassumedhoststate=0&initialassumedservicestate=0&assumestateretention=yes&includesoftstates=no&host=SCP-3&service=MODIFICATION+TIME+EDR+FILES&backtrack=4&zoom=4";
//we'll use an in-memory "hyperlink" object for basic parsing
var anchor = document.createElement("A");
anchor.href=linktext;
//the query string starts with ?, we remove it.
//then, split it by & symbol
var queryvars = anchor.search.replace(/^\?/, '').split('&');
//now looping through all parts of query string, creating an object in form key->value
var querycontent = {};
for( i = 0; i < queryvars.length; i++ ) {
var queryvar = queryvars[i].split('=');
querycontent[queryvar[0]] = queryvar[1];
}
//this allows us to reference parts of the query as properties of "querycontent" variable
querycontent.service = "AnotherService"
//TODO: change the properties you actually need
//and now putting it all back together
var querymerged = [];
var g = "";
for (var key in querycontent){
var fragment = key;
if (querycontent[key]) {
fragment += "=" + querycontent[key];
}
querymerged.push(fragment);
}
anchor.search = querymerged.join("&")
//finally, access the `href` property of anchor to get the link you need
document.getElementById("test").innerText=anchor.href;

Categories