How to return json object by variable? - javascript

I want to return from JSON object "mail" for "name" which will be definie by variable C.
var c = "product3"
var text = '{"products":[' +
'{"name":"product1","mail":"jan#mail.com" },' +
'{"name":"product2","mail":"anna#mail.com" },' +
'{"name":"product3","mail":"john#mail.com" }]}';
In this case i want to return product3 john#mail.com

Using ES2015
let productsArr = JSON.parse(text).products;
let result=productsArr.find(product=>product.name===c);
console.log(result.mail);// output john#mail.com

You can do it with ES6's find easily,
var textObj = JSON.parse(text)
var mail = textObj.products.find(itm => itm.name == c).mail
console.log(mail); // "john#mail.com"
DEMO

You can use Array.prototype.filter to return only values of your array which have a name === "product3".
var obj = JSON.parse(text);
var c = "product3";
var requiredProduct = obj.products.filter(function(x) {
return x.name === c;
});

var text = '{"products":[' +
'{"name":"product1","mail":"jan#mail.com" },' +
'{"name":"product2","mail":"anna#mail.com" },' +
'{"name":"product3","mail":"john#mail.com" }]}';
var data = JSON.parse(text);
var data1 = data.products;
console.log(data1[2].name)//get 3rd
console.log(data1[2].mail)//get 3rd
for (var i = 0; i < data1.length; i++) {
console.log(data1[i].name)//iterate here
console.log(data1[i].mail)//iterate here
}
Do it like this

first change var text to
var text = {"products": [
{"name":"product1","mail":"jan#mail.com" },
{"name":"product2","mail":"anna#mail.com" },
{"name":"product3","mail":"john#mail.com" }
]};
then you can access the values as follows
var c = text.products[2].name //returns product3
var email = text.products[2].mail //returns john#mail.com
Hope this helps.

Related

How to combine similar values in a comma separated string in JQuery

I have string with values :
var string = 1-1, 1-2, 2-8, 2-10, 3-13, 3-14, 3-15,
now i want to combine them as follow:
var result = 1-1,2| 2-8,10| 3-13,14,15
How to achieve this in JQuery or Javascript.
var string = "1-1, 1-2, 2-8, 2-10, 3-13, 3-14, 3-15";
var result_array = [];
string.split(",").forEach(function (item) {
var first_number = item.trim().split("-")[0];
var second_number = item.trim().split("-")[1];
if (!result_array[first_number]) {
result_array[first_number] = [];
}
result_array[first_number].push(second_number);
});
var ordered_result = [];
result_array.forEach(function (content, index) {
ordered_result.push(index + "-" + content.join(","));
});
var result = ordered_result.join("| ");
console.log(result);

Node Red multiple values to influxDB

i try with Node Red to build an query to send multiple values to an influxDB from a loop with this code:
var inputArray = msg.payload;
var lenInputArray =inputArray.length;
var modbusStartRegister = 14000;
var sendString = "";
var msg93 ={};
for (i = 0; i < lenInputArray; i++) {
var actRegister = modbusStartRegister +i;
var actValue = inputArray[i];
if ( i >=1){
sendString = sendString + " ,"
}
sendString = sendString +"{register: " + actRegister +"," +"value: " + actValue +"}";
if ( i ==(lenInputArray-1)){
sendString = sendString + "]"
}
}
msg93.payload = sendString;
return msg93
But the insert in the influxDB is one line it looks at them interpreted as an complete string. How can I build or convert the string that the DB accept them as individual entry? Thanks for the help
This is because you are building a string, node an object.
You can build the array object on the fly like this:
var inputArray = msg.payload;
var lenInputArray =inputArray.length;
var modbusStartRegister = 14000;
var payload = [];
var msg93 ={};
for (i = 0; i < lenInputArray; i++) {
var temp = {};
temp.register = modbusStartRegister +i;
temp.value = inputArray[i];
payload.push(temp);
}
msg93.payload = payload;
return msg93

How can I put all the URL parameters in array of objects using jQuery?

I have a giving string/url like this
https://example.com/loadcontent?var1=100&var2=:somevar&var3=:morevariables
I need to loop thought each parameter in the url. If the value starts with : this indicated that it is a variable an I will need to change that value dynamically by looking at the corresponding meta attribute that matches that variable.
Here is my code in which loops over an array and sets the value of the parameters.
var baseURL = getBaseURL(url);
var params = getParams(url);
var newParams = $.each(params, function(index, param){
if( param.value.substring(0, 1) == ':'){
var myVar = param.value.substring(1);
param.value = $('meta[name=" + myVar + "']).attr('value');
}
});
var finalURL = baseURL + '?' + jQuery.param( newParams );
function getParams(url){
// This function should return an array of objects. Each object should have 2 properties "value" and "name". The "name" property should be the name of the parameter (ie. var1, var2, var3 .....) and the "value" attribute should contains the value of the parameter (ie. 100, :somevar, :morevariables)
}
function getBaseURL(url){
var cutoff = url.indexOf('?');
if( cutoff > -1){
return url.substring(0, cutoff - 1);
}
return url;
}
I need help converting the parameters of a giving URL to array of object. How can I do this in jQuery?
You dont need jQuery for this one.
function getParams(url) {
var queryString = url.substring(url.indexOf('?') + 1);
var paramsArr = queryString.split('&');
var params = [];
for (var i = 0, len = paramsArr.length; i < len; i++) {
var keyValuePair = paramsArr[i].split('=');
params.push({
name: keyValuePair[0],
value: keyValuePair[1]
});
}
return params;
}
Here is an example using map
var url = 'https://example.com/loadcontent?var1=100&var2=:somevar&var3=:morevariables&test';
function getParamArray(url) {
var queryString = url.substring(url.lastIndexOf("?") + 1);
return queryString.split('&').map(function(sParam) {
var param = sParam.split('=');
return {
name: param[0],
value: decodeURIComponent(param[1])
};
});
}
document.getElementById("output").innerHTML = JSON.stringify(getParamArray(url), null, 2);
<pre id="output"></pre>
With a regular expresion and JSON.parse:
var url = 'https://example.com/loadcontent?var1=100&var2=:somevar&var3=:morevariables';
url = url.replace(/^.*\?/,'');
url = url.replace(/(\w+)=?([\w:]*)/g,'{"name":"$1","value":"$2"}');
url = url.replace(/&/g,',');
var paramsObject = JSON.parse("["+url+"]");
/*
Returns:
Array [{"name":"var1","value":"100"},{"name":"var2","value":":somevar"},{"name":"var3","value":":morevariables"}];
*/
You don't even need JQuery for this.
<script type="text/javascript">
var paramStr = window.location.search;
var params = paramStr.substring(1, paramStr.length).split('&');
var paramList = [];
for (var index=0; index < params.length; index++) {
var param = params[index].split('=');
paramList.push({name: param[0], value: param[1]});
}
</script>
The result:
[Object]0: Object
name: "a"
value: "b"
...
var url=new URLSearchParams(window.location.search);
var params = [];
for(var value of url.keys())
{
params.push({
name: value,
value: url.get(value)
});
}

how to get length of an ajax object

I would like to get the length of the 'obj' object so that I can do a for-loop with it, here is my code:
var oRequest = new XMLHttpRequest();
var sURL = "/Users/files/Documents/time.json";
oRequest.open("GET",sURL,false);
oRequest.send();
var txt = oRequest.responseText;
var obj = eval ("(" + txt + ")");
My goal is that I would like to output everything in this time.json file to the screen.
Here is what my json file looks like:
{
"employees": [
{ "firstName":"John" , "lastName":"Doe" },
{ "firstName":"Anna" , "lastName":"Smith" },
{ "firstName":"Peter" , "lastName":"Jones" }
]
}
The object you create does not have have a length. I assume you meant employees length and not the obj length
Like this:
Live Demo
var txt = oRequest.responseText;
// eval("var obj = "+txt); // eval is not recommended but here is how
var obj = JSON.parse(txt); // this is better
var emp = obj?obj.employees:[]; // if we have a useful object, get the employees
window.onload=function() {
var empDiv = document.getElementById("empDiv");
for (var i=0;i<emp.length;i++) {
empDiv.innerHTML+=emp[i].firstName + " "+ emp[i].lastName + '<br/>';
}
}
you don't have to get a length in order to do a for loop on an object, based on your object structure you can get data with the following loop:
for(var key in object) {
var o = object[key];
for(var i = 0; i < o.length; i++) {
var user = o[i];
alert(user.firstName);
}
}

Javascript location.search

How could I specifically get every of these query strings in
file:///K:/CKaing_C20_A01_Casino2/game.html?First+Name=Testfirst&Last+Name=Testlast&pnum=123-456-7890&postCode=A1A+1A1&startMoney=5000
For example, I want to get Testfirst, and then assign it to a variable so I can use it later on. Same thing with the others.
This is what I have so far to remove all the +, =
var formData = location.search;
formData = formData.substring(1, formData.length);
while (formData.indexOf("+") != -1) {
formData = formData.replace("+", " ");
}
formData = unescape(formData);
var formArray = formData.split("&");
for (var i=0; i < formArray.length; ++i) {
document.writeln(formArray[i] + "<br />");
}
var splitSearch = JSON.parse("{\""+(location.search.substr(1).replace(/\=/g,"\"\:\"").replace(/\&|(\/\?)/g,"\", \""))+"\"}")
I made that one for a webpage that uses a rare ("/?") separator too.
http://example.com/?a=0&b=bee/?c=third
First one will work for URLs like that
If you want it for a conventional location:
var splitSearch = JSON.parse("{\""+(location.search.substr(1).replace(/\=/g,"\"\:\"").replace(/\&/g,"\", \""))+"\"}")
Once splitSearch is defined you can get "pnum" string like this:
splitSearch.pnum
splitSearch["pnum"]
Another way to get it:
var splitSearch = JSON.parse("{\""+(location.search.substr(1).replace(/(\=)|(\&)|(\/\?)/g, function(k) {
var rtn=k;
if (k == "\=") rtn="\"\:\"";
else if ((k == "\&") /*|| (k == "\/\?")*/) rtn="\",\"";
return rtn;
})+"\"}"))
A mix of use of replace with regEx and the split function does the work.
var str = "file:///K:/CKaing_C20_A01_Casino2/game.html?
First+Name=Testfirst&Last+Name=Testlast
&pnum=123-456-7890&postCode=A1A+1A1&startMoney=5000";
var argStrIndex = str.indexOf("?");
var argStr = str.substring(argStrIndex+1);
var args = argStr.replace(/\+/g," ").split("&");
for (var i=0;i<args.length;i++){
alert(args[i]);
}
demo: http://jsfiddle.net/7meAv/
something like that :
var search = location.search
.replace(/^\?/,'')
.replace(/\+/g,' ')
.split('&')
.map(function(string){
var split = string.split('=');
var res={};
res[split[0]]=split[1];
return res;
});
should return
[{"First Name":"Testfirst"},{"Last Name":"Testlast"},{"pnum":"123-456-7890"},{"postCode":"A1A 1A1"},{"startMoney":"5000"}]"
You'd need to take care of url encoding though.
A combination of the two answers already given (jsfiddle: http://jsfiddle.net/russianator/GymEq/)
var url = 'file:///K:/CKaing_C20_A01_Casino2/game.html?First+Name=Testfirst&Last+Name=Testlast&pnum=123-456-7890&postCode=A1A+1A1&startMoney=5000';
queryObject = {};
url.substring(url.indexOf('?')+1)
.replace(/\+/g,' ')
.split('&')
.forEach(function(item) {
splitItem = item.split('=');
queryObject[splitItem[0]] = splitItem[1];
});
Returns an object like this:
{
"First Name": "Testfirst",
"Last Name": "Testlast",
...
}

Categories

Resources