This is a basic question in JavaScript. I tried a lot playing around this, but i can't the solution.
I have an array.
var keys = ["a", "b", "c"];
var array =[];
I am looping this keys to form another array
for (var i =0; i<keys.length; i++){
array[i]= "x" + keys[i];
}
If i print this array
i got ['xa']; but what i needed is ["xa"]
only difference is the quotes ""..
Why because i have to use this array in another json as with double quotes. Thanks in advance..
consider my json array name as final,
var query = {
"_source": {
"include": final
}.
NOw here the query is forming like
var query = {
"_source": {
"include": '["xa"]'
}
But i need:
var query = {
"_source": {
"include": ["xa"]
}
I think you are confused about what you are seeing printed in your console. Strings don't inherently have either single or double quotes associated with them. So, it doesn't matter if your browser displays it as ['a','b','c'] or ["a","b","c"]. The array still contains the same thing. What you DO care about is how it is converted into a string, as you stated in your question. You said you need it to use double quotes. Try using JSON.stringify(). You will notice that this outputs a string in the format you want. Here is a short example:
var myArray = ['a', 'b', "c"];
// notice I even used a mix of single and double quotes in the declaration
var arrayAsString = JSON.stringify(myArray);
console.log(arrayAsString);
The output will be:
["a","b","c"]
If you can pass just through via json it mustn't be problem but if you first read it as a string and after you use that string as an argument, you can use replace function. You can do it as I gave here.
How to replace all occurrences of a string in JavaScript?
Use single quotes and put double quotes inside of it.
array[i]= '"x' + keys[i] + '"';
Related
I have an array that comes in from from my API that I would like to arrange in a way that is better for the user (namely, in a column as opposed to the typical comma separated printed array).
This is my JS Fiddle to give a clearer picture: https://jsfiddle.net/2z89owas/
My question is, how can I get output3 to display just like output (and maintain its status as an iterable array like it was as dates)?
First you should not be using value for an html element. You can use .value for extracting value from inputs. Change your line to:
var val = document.getElementById('output2').innerHTML;
Afterwards, you have to split the same way you did join.
var dates3 = val.split('<br>');
document.getElementById('output3').innerHTML = dates3;
You can directly use join, something like:
document.getElementById('output3').innerHTML = dates.join(',');
You can try mapping over the contents of dates instead, as so:
let datesElem = dates.map(date =>`<p>${date}</p>`);
// test: console.log(datesElem)
document.getElementById('output3').innerHTML = datesElem
Okay, so I have a filepath with a variable prefix...
C:\Users\susan ivey\Documents\VKS Projects\secc-electron\src\views\main.jade
... now this path will be different for whatever computer I'm working on...
is there a way to traverse the string up to say 'secc-electron\', and drop it and everything before it while preserving the rest of it? I'm familiar with converting strings to arrays to manipulate elements contained within delimiters, but this is a problem that I have yet to come up with an answer to... would there be some sort of regex solution instead? I'm not that great with regex so I wouldn't know where to begin...
What you probably want is to do a split (with regex or not):
Here's an example:
var paragraph = 'C:\\Users\\susan ivey\\Documents\\VKS Projects\\secc-electron\\src\\views\\main.jade';
var splittedString = paragraph.split("secc-electron"); // returns an array of 2 element containing "C:\\Users\\susan ivey\\Documents\\VKS Projects\\" as the first element and "\\src\\views\\main.jade" as the 2nd element
console.log(splittedString[1]);
You can have a look at this https://www.w3schools.com/jsref/jsref_split.asp to learn more about this function.
With Regex you can do:
var myPath = 'C:\Users\susan ivey\Documents\VKS Projects\secc-electron\src\views\main.jade'
var relativePath = myPath.replace(/.*(?=secc-electron)/, '');
The Regex is:
.*(?=secc-electron)
It matches any characters up to 'secc-electron'. When calling replace it will return the last part of the path.
You can split the string at a certain point, then return the second part of the resulting array:
var string = "C:\Users\susan ivey\Documents\VKS Projects\secc-electron\src\views\main.jade"
console.log('string is: ', string)
var newArray = string.split("secc-electron")
console.log('newArray is: ', newArray)
console.log('newArray[1] is: ', newArray[1])
Alternatively you could use path.parse(path); https://nodejs.org/api/path.html#path_path_parse_path and retrieve the parts that you are interested in from the object that gets returned.
When i try to put an array into a JavaScript array, a la,
> `${[1,2,3]}`
I get back this
'1,2,3'
and not
'[1,2,3]'
in the latest Node & Chrome.
I am missing something incredibly obvious, but need it spelled out to me nevertheless : )
You should use JSON.stringify(array)
It can help you to predict conversion to the string any arrays in this array.
const array = [["expected","test",1],0];
const arrayStr = JSON.stringify(array);
const templateResAsString = `${array}`; // expected,test,1,0
const templateResAsarray = `${arrayStr}`; // [["expected","test",1],0]
By the default, the values that are interpolated into a template literal are converted to their string representation.
For objects that means calling their .toString() method. The string representation of an array is simply a comma separated list of the strings representation of its elements, without leading [ or trailing ]:
console.log(
[1,2,3].toString()
);
Consolodiated list including above answers:
const arr = [1,2,3,4,5,'foo','bar','baz']
console.log(JSON.stringify(arr));
console.log(JSON.stringify(arr, null, 2));
console.log(arr.toString());
console.log(`${arr}`);
console.log(arr.join('\n'));
Good Luck...
How can a javascript Array be stored in an HTML5 data attribute?
I've tried every variation of JSON.stringifycation and escaping characters.
What is the precise method to store the array and retrieve it again?
note
I build the array with [ $("#firstSelectedElement").val(), $("#secondSelectedElement").val() ]. I retrieve id="storageElement" data-storeIt="stuff" with $("#storageElement").data('storeit').
I can never seem to retrieve the data as a true Array, only an Array of characters.
It turned out that you could use the html escaped characters in the element data attribute to have json-like array (encoded are quotes):
<div id="demo" data-stuff='["some", "string", "here"]'></div>
And then in javascript get it without any additional magic:
var ar = $('#demo').data('stuff');
Check this fiddle out.
Edited (2017)
You don't need to use html escaped characters in the data attribute.
<div id="demo" data-stuff='["some", "string", "here"]'></div>
Check this new fiddle out.
It depends on what type of data you're storing in the array. If it's just strings (as it appears to be) and you have a character that you know will never be a part of your data (like the comma in my example below) then I would forget about JSON serialization and just use string.split:
<div id="storageElement" data-storeIt="stuff,more stuff"></div>
Then when retrieving:
var storedArray = $("#storageElement").data("storeIt").split(",");
It will handle a bit better than using JSON. It uses less characters and is less "expensive" than JSON.parse.
But, if you must, your JSON implementation would look something like this:
<div id="storageElement" data-storeIt='["hello","world"]'></div>
And to retrieve:
var storedArray = JSON.parse($("#storageElement").data("storeIt"));
Notice that in this example we had to use semi-quotes (') around the data-storeIt property. This is because the JSON syntax requires us to use quotes around the strings in its data.
The HTML5 data attribute can store only strings, so if you want to store an array you will need to serialize it. JSON will work and it looks like you're on the right path. You just need to use JSON.parse() once you retrieve the serialized data:
var retrieved_string = $("#storageElement").data('storeit');
var retrieved_array = JSON.parse(retrieved_string);
Reviewing the api documentation, jQuery should try to automatically convert a JSON encoded string provided it is properly encoded. Can you give an example of the value you are storing?
Also note that HTML5 data attribute and jQuery .data() methods are two distinct things. They interact, but jQuery is more powerful and can store any data type. You could just store a javascript array directly using jQuery without serializing it. But if you need to have it in the markup itself as an HTML5 data attribute, then you are limited only to strings.
For the record, it didn't work with encoded entities for me, but seems that in order to be parsed as an object, the data attribute must be a well formed JSON object.
So I was able to use an object with:
data-myarray="{"key": "value"}"
or maybe just use single quotes:
data-myobject='{"key1": "value1", "key2": value2}'
Time to have fun! :D
You can store any object into node like that:
$('#storageElement').data('my-array', ['a', 'b', 'c']);
var myArray = $('#storageElement').data('my-array');
If you need nested arrays or just another way to do it. This works:
$('[data-example]').each(function (i, e) {
var json = $(e).data('example');
for(var index in json){
console.log(json[index]["name"] + "=" + json[index]["value"]);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div data-example='[{"name": "A", "value": 1}, {"name": "B", "value": 2}]' />
<div data-example='[{"name": "C", "value": 3}, {"name": "D", "value": 4}]' />
as suggested by Ulysse BN
Or with eval() that is a dangerous solution as pointed by Bonifacius Sarumpaet but works
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div data-example="[['A', 1], ['B', 2]]" />
<div data-example="[['C', 3], ['D', 4]]" />
<script>
$('[data-example]').each(function (i, e) {
var arrayFromText = eval($(e).data('example'));
console.log(arrayFromText[0][0] + "=" + arrayFromText[0][1]);
console.log(arrayFromText[1][0] + "=" + arrayFromText[1][1]);
});
</script>
If using PHP do in PHP:
$arr_test = ['A','C','E'];
$coded = json_encode($arr_test);
// paste coded in data-atribute
print '<div class="funPlus" data-arr_diensten="'. $coded . '"></div>';
The HTML on inspect looks like:
<div class="funPlus" data-arr_diensten="["A","C","E"]"></div>
Now in javascript retrieve the array, but if it has only one value it returns as a string. So you have to test and fix this. If it is a string we have to remove the extra quotes. $(this) has to point to the object.
var arr_diensten = $(this).data("arr_diensten");
if (typeof arr_diensten == "string") arr_diensten = [arr_diensten.slice(1, -1)];
console.log(arr_diensten);
This is probably very elementary, but I'm still learning.
I've imported a record from an XML file and have the result :
"a,b,c,d,e,f,g,h"
I would like to end up with 8 separate variables, one for each comma delimited value.
What is the shortest way to code this using javascript?
if you .split() the list, you'll end up with a single array with 'n' number of elements. Not -exactly- 8 separate variables, but 8 elements that can be accessed individually.
var myList = "a,b,c,d,e,f,g,h";
var myArray = myList.split( ',' );
alert( myArray[ 4 ] );
use split()
js>s = "a,b,c,d,e,f,g,h"
a,b,c,d,e,f,g,h
js>a = s.split(',')
a,b,c,d,e,f,g,h
js>a[0]
a
js>a[4]
e
Use split().
In your case, xml_string.split(',');
If you have the result as a string, use the split method on it:
var myList = "a,b,c,d,e,f,g,h";
var myArray = myList.split(",");