Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
How can I convert the following string using JavaScript to array:
from: var x = "{id:'2'},{name:'code,Barer'}";
to: var x1 = [{id:"2"},{name:"code,Barer"}];
If you want that exact string to be an array object you can do this:
var x = "{id:'2'},{name:'code,Barer'}";
var newArray = eval("[" + x + "]");
Here are some the dangers of eval: Why is using the JavaScript eval function a bad idea?
How are you getting the variable x? If you can get whatever it is to spit out valid JSON (using JSON.stringify or something similar) you can then parse it correctly into JS (although some implementations of JSON parsers do use eval).
If you want to avoid using eval for security reasons try this
var string = "{id:'2'},{name:'code,Barer'}",
array = string.substr(1, string.length - 2)
.split("},{")
.map(function(item){
item = item.split(":");
var result = {},
name = item[0],
value = item[1].replace(/'/g, "");
result[name] = value;
return result
});
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I have keyword (for example -2330) that needs to be compared with the 'values' in this string below.
"[{\"type\":\"A_PRODUCT\",\"value\":[[{\"key\":\"SUBCLASS\",\"value\":\"1574\"}],[{\"key\":\"SUBCLASS\",\"value\":\"2331\"}]]}]";
Expected output needs to be true or false depending if the string has the keyword or not.
How do I check it?
I will do something like this to loop
var a = "[{\"type\":\"A_PRODUCT\",\"value\":[[{\"key\":\"SUBCLASS\",\"value\":\"1574\"}],[{\"key\":\"SUBCLASS\",\"value\":\"2331\"}]]}]";
var new_a = JSON.parse(a);
var value_compare = '1574';
new_a[0]['value'].forEach(element => {
if (element[0].value == value_compare) {
//DO SOMETHING
alert('found: '+ JSON.stringify(element));
}
});
You first need to parse the JSON into an suitable JS structure. Because of the nested nature of the data you need to 1) map over the first object in your array, 2) return the value of the value property of the first object of each and finally 3) check to see if the keyword is included in the the returned array, and return true or false.
const json = '[{\"type\":\"A_PRODUCT\",\"value\":[[{\"key\":\"SUBCLASS\",\"value\":\"1574\"}],[{\"key\":\"SUBCLASS\",\"value\":\"2331\"}]]}]';
const data = JSON.parse(json);
function doesItExist(data, keyword) {
const values = data[0].value.map(arr => arr[0].value);
return values.includes(keyword);
}
console.log(doesItExist(data, '2331'));
console.log(doesItExist(data, 'Bob'));
console.log(doesItExist(data, '1574'));
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
https://jsfiddle.net/a/2L4t9saq/217/ is my fiddle
most of the code you can ignore, here is the function:
var modGrid = function(code){
var arr = code
console.log(arr)
for(var n=1;n<gridx+1;n++){
for(var i = 1; i<gridy+1; i++){
var garbledMess = "[x="+i+"][y="+n+"]"
var idea = arr[0]
arr.shift()
$(garbledMess).css("background-color",idea)
}
}
}
the syntax error is as follows:
Uncaught TypeError: arr.shift is not a function
at modGrid ((index):44)
at window.onload ((index):81)
since the modGrid function takes in an array (in the case of my code an array of 4 elements) the .shift() function should be removing the first option in the array, it worked before i added some more code, but now it is apparently not a function
many thanks
since the modGrid function takes in an array
It is designed to take an array, but that isn't what you are passing it.
You are passing it a string, another string, a number and another number.
modGrid('rgba(255,0,0,1)','rgba(0,255,0,1)',2,1);
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
I have 2-9 value stored in a single variable in JavaScript.
But I want 2 to be stored in a variable and 9 stored in b variable.
For example :
<script>
var a = "2-9";
</script>
And I want to,
<script>
var a = "2";
var b = "9";
</script>
Please help me.
You could use the charAt() method of String in javascript.
var a = string.charAt(0);
var b = string.charAt(2);
where string is "2-9".
I suppose that your string, wouldn't have the form "2-10", because in this case that will not work.
If that's the case then you have to use the split() method of String in javascript.
var c = string.split('-');
var a = c[0];
var b = c[1];
For futher documentation about these methods in javascript plese refer to the following links:
JavaScript String charAt() Method
JavaScript String split() Method
use .split() in javascript
var a = "2-9";
var c = a.split("-");
a = c[0]; // it returns 2
var b = c[1]; // it returns 9
You can use .split():
The split() method splits a String object into an array of strings by
separating the string into substrings.
var a = "2-9",
b = a.split('-')[1];
a = a.split('-')[0];
Fiddle Demo
What you can do is this:
<script>
var string_value = "2-9".split('-'),
minimum_name = string_value[0], // 2
maximum_name = string_value[1]; // 9
</script>
Make use of .split() which creates an array out of a string, so you can split it by - then you can assign the values with their indexes like [0], [1].
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am passing Latitude and Longitude by link to direction.html file
.../direction.html?latlng=53.456269068499545,-6.220780313014984
how can I get this values to get lat and lng separately
You can use hashtag, that is passing the value latitude and longitude like this
ursite/path#53.456269068499545,-6.220780313014984
var tag = window.location.hash;
tag = tag.substring(1,tag.length);
var co_ordinate = tag.split(",")
var latlng = co_ordinate[0]
var logitude = co_ordinate[1];
Because you're passing a single variable, you could just split the data using the comma. The result would be an array.
latlng=53.456269068499545,-6.220780313014984
var res = latlng.split(",");
http://www.w3schools.com/jsref/jsref_split.asp
Well Im not sure what language you are using to script the page. I have ideas for PHP.
//you get the variable being passed
if (isset ($_Get['longlat'];) {
$longlat = $_GET['longlat'];
//then you split them with explode
$longlat = explode(',', $longlat);
$long = $longlat[0];
$lat = $longlat[1];
thats about it. read the manual on explode to get the correct syntax, but this is the gist of what you want i believe
You can use split to pull the string into an array, splitting it by the comma, then just assign each of the array's values to a new variable for lat and lng.
I would also parse the data into floats if you are using it as actual coordinate data later on, rather than just printing it.
For:
String latlng=53.456269068499545,-6.220780313014984;
Use:
var coords = latlng.split(",");
float lat = parseFloat(coords[0]);
float lng = parseFloat(coords[1]);
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am quite new to using Node.js. I was looking for a good way to parse and query a JSON object. I have the following JSON object loaded in as a file.
[
{"Key":"Accept","Values":["Application/x-www-form-urlencoded","Application/Json","Application/Xml"]},
{"Key":"Accept-Charset","Values":["UTF-8", "ISO-8859-1"]},
{"Key":"Accept-Encoding","Values":["compress", "gzip"]},
{"Key":"Accept-Language","Values":[]},
{"Key":"Accept-Ranges","Values":[]},
{"Key":"Age","Values":[]},
{"Key":"Allow","Values":[]},
{"Key":"Authorization","Values":["Bearer"]},
{"Key":"Cache-Control","Values":[]},
{"Key":"Connection","Values":[]},
{"Key":"Content-Encoding","Values":[]},
{"Key":"Content-Language","Values":[]},
{"Key":"Content-Length","Values":[]},
{"Key":"Content-Location","Values":[]},
{"Key":"Content-MD5","Values":[]},
{"Key":"Content-Range","Values":[]},
{"Key":"Content-Type","Values":["Application/x-www-form-urlencoded","Application/Json","Application/Xml"]},
{"Key":"Date","Values":[]},
{"Key":"ETag","Values":[]},
{"Key":"Expect","Values":[]},
{"Key":"Expires","Values":[]},
{"Key":"From","Values":[]},
{"Key":"Host","Values":[]},
{"Key":"If-Match","Values":[]},
{"Key":"If-Modified-Since","Values":[]},
{"Key":"If-None-Match","Values":[]},
{"Key":"If-Range","Values":[]},
{"Key":"If-Unmodified-Since","Values":[]},
{"Key":"Last-Modified","Values":[]},
{"Key":"Max-Forwards","Values":[]},
{"Key":"Pragma","Values":[]},
{"Key":"Proxy-Authenticate","Values":[]},
{"Key":"Proxy-Authorization","Values":[]},
{"Key":"Range","Values":[]},
{"Key":"Referer","Values":[]},
{"Key":"TE","Values":[]},
{"Key":"Trailer","Values":[]},
{"Key":"Transfer-Encoding","Values":[]},
{"Key":"Upgrade","Values":[]},
{"Key":"User-Agent","Values":[]},
{"Key":"Via","Values":[]},
{"Key":"Warning","Values":[]}
]
I want to be able to find a Key by value and return the values array.
So for example how do I find the values where the key is equal to Content-Type.
Thanks in advance for your help
Since you're using Node.js, you can take advantage of the newer Array.prototype.filter
var myData = require('./data.json'),
myFilteredData = myData.filter(function(obj) {
return obj.key === 'Content-Type';
});
My comment notwithstanding, I would loop through the array like so:
function searchByKey(key) {
for (var i = 0, l = arr.length; i < l; i++){
if (arr[i]['Key'] === key) {
return arr[i]['Values'];
}
}
return false;
}