How to access a variable using a string in javascript? - javascript

I receive in input a string that should be the name of an array. How do I call the array as a variable and not a string?
<div onclick="smt(this.id)" id="name"></div>
<script>
name=[...]
function smt(id){
?
}

Related

Passing array of strings to a function in a string literal

When I pass an array of strings and an index to an onclick event, the callback function receives the parameters from the first two values of the array as a number instead of the array and the index.
I have tried to convert it to an array using the Array.from function.
let presentantes = ["28411", "199904", "214966", "16226"];
console.log('presentantes', presentantes);
//presentantes (4) ["28411", "199904", "214966", "16226"]
let id = 1
let listNominated = `<li onClick="cargaPresentantes(${presentantes}, ${i})">`
function cargaPresentantes(presentantes, id) {
console.log('presentantes', presentantes);
console.log('id', id)
//presentantes 28411
//id 199904
}
I was expecting to get an array ["28411", "199904", "214966", "16226"] and the index 1
Actually template literals work something like this - If the variable which is passed to the placeholder is not a string(an array in this case) then it CONVERTS it to string.
So in your code the value of listNominated becomes '28411,199904,214966,16226,1' and thus it takes the first two arguements i.e. 28411 and 199904.
You cannot pass the parameters in that way... you should create a “onclick listener function” and then associate it to the “li” element.
As Andrea said I had to add an onclcik listener function. To do this, I had to append the string literal to the document first.

Python Dictionary Object Conversion to JSON when Output Through Template

I am using the Flask framework to obtain a dictionary object with the key set to the user ID and the value set to the username. From the view in Flask I am converting it to json using jason.dumps and when rendering the template, outputting direct to the Javascript code for example:
<script type="text/javascript">
var = {{ users }};
...
</script>
When I examine the rendered HTML code the string value outputted looks as below, example given for one user:
var = {"5d626ba11c9d4400004665b5": "shears"};
As you can see it is encoding the quote characters to their character value. How do I get this to output as a JSON object in the Javascript?
You could render a template variable inside a string, unescape HTML and then parse the result as JSON.
function unescapeHtml(safe) {
return $('<div />').html(safe).text();
};
var usersDict = JSON.parse(unescapeHtml('{{ users }}'));
The usersDict variable is an object:
Object { 5d626ba11c9d4400004665b5: "shears" }
Hope this helps.

How to convert JavaScript object to a normal string?

I want to post a variable through AJAX.
The typeof variable is "object".
If I directly post an object, the AJAX fails. I used JSON.stringify but then it’s in ["10","11","12"] format.
I need a string similar to 10,11,12. How do I do that?
Just call method join on your array like this :
console.log(["10","11","12"].join(",")); // 10,11,12
The String() function converts the value of an object to a string. The String() function returns the same value as toString() of the individual objects.
function myFunction() {
var x1 = ["10","11","12"];
var res = String(x1) + "<br>";
document.getElementById("demo").innerHTML = res;
}
<p>Click the button to convert object to string.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
Seems like this was an array so toString() should do it.
but ["10","11","12"] was the correct representation of the javascript object.
[] tells it was an array, that information is permanently lost when you generate something like 10,11,12

Cant extract variable data into a string format for passing to a db

Currently I have all the following held within a variable.(badgeselected). Which returns the following in console.log
[<img id=​"go" src=​"http:​/​/​kudosoo.com/​Pics/​Lisa_Wong.jpg" alt=​"img" style=​"cursor:​ pointer;​">​ , <div id=​"go">​</div>​ ]
Using js/juery I'd like to extract just the url so I can store it in a db as a string
How can I do this? At the moment I have the variable defined as the following, but I'm not sure if .val is correct to turn it into a string?
var badgeselected = $("#badge").val();
Just do this
$("#badge").attr("src")

Variable name is getting added instead of its value , in javascript object [duplicate]

I have a problem while adding values to a JavaScript object: the value to add is a key,value pair. Here is sample:
//JavaScript object
var cart=new Object();
function add()
{
var rating="1"
var category="somecat";
var user="user1";
if(cart[user]==null)
cart[user]={category:rating};
else
cart[user][category]=rating;
}
What I was expecting is that if user exists in cart object then value for his particular should get replaced, and if user doesn't exist then new user and category should be added.
The code is working fine when user already exists. Problem is, when I am adding a new element with cart[user]={category:rating} then its adding the variable name as key i.e. category , not the value inside it ("somecat").
Is there any way to do this using json, jquery or javascript itself?
Is there any way to assign value inside the variable?
There is no way to use a variable to define a property name inside object literal notation. It accepts identifiers or strings, but both identify property names, not variables.
You have to create the object then add the property:
if(!cart[user]) {
cart[user] = {};
}
cart[user][category] = rating;
You will need to replace
{category:rating}
with
var obj = {};
obj[category] = rating;
When creating an object literal the key must be a string, so in your code it will be "category". If instead you do:
var rating="1"
var category="somecat";
var user="user1";
if( !cart[user] ) {
cart[user]={};
}
cart[user][category]=rating;
That will initialise a non existing user to an empty object and then add the category.

Categories

Resources