Passing array of strings to a function in a string literal - javascript

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.

Related

How to show only 20 object from Array in typescript?

I am using angular 7. I have initialized an array given as:
cacheDatas=[];
Here cacheData has 1000 of object which are initialized to cacheDatas but I only need 20 object.
getDataOfCache(cacheData:any){
this.cacheDatas=cacheData;
this.cacheDatas.slice(0,20);
console.log(this.cacheDatas);
}
I tried to implement the slice method but it is not working. The value cacheData:any is:
Need to assign the value for the variable: cacheDatas after slice.
this.cacheDatas = this.cacheDatas.slice(0,20);
Example here: https://stackblitz.com/edit/angular-3d4ypz
you can use splice method but this method will method changes the contents of an array by removing
this.cacheDatas.splice(20);
another option is the slice method same as you question but this methos method returns a shallow copy of a portion of an array into a new array object
const result = this.cacheDatas.slice(0,20);
console.log(result)
slice() method does not modify the array but returns a new array with the required elements. So you can use the below to solve your problem -
getDataOfCache(cacheData:any){
this.cacheDatas=cacheData;
this.cacheDatas=this.cacheDatas.slice(0,20);
console.log(this.cacheDatas);
}
Or you can use the splice() method (note the change in spelling). It will modify the original array as per the given input. If only one index is given as input, then it will remove all the elements from that index to the end of the array. So you can use this code as well -
getDataOfCache(cacheData:any){
this.cacheDatas=cacheData;
this.cacheDatas.splice(20);
console.log(this.cacheDatas);
}

Adding a different value of the same variable to an array

Using my micro:bit I am trying to add the value of a variable called sendText to an array without overwriting its previous stored value for that variable.
input.onGesture(Gesture.Shake, () => {
list.push(sendText)
binSend = 0
basic.showString(sendText)
})
My array is called list
let list: string[] = []
I am trying to store single characters in an array then outputting them. If there is a better alternative to using an array I would gladly accept it.
To add a value to an array you use push function, after, if you need to group the characters pushed to array for output you could to use for your specific example list.join('')

How to convert a javascript map of array into a json object in javascript?

I have a javascript MAP object which is holding key as a string and value as a javascript array, each array is holding set of strings inside it. I want to convert the map of arrays into a json object in javascript.
Here is the code which i tried
function addRole() {
var jsonObjectOfMap={};
subMenuSelectedIdMap.forEach(function(items,key,subMenuSelectedIdMap){
jsonObjectOfMap[key]=JSON.stringify(items);
});
alert(JSON.stringify(jsonObjectOfMap));
I am getting the json object as like this
{"1004":"[1005,1006,1023]","1007":"[1008,1053]"}
But is this json format object is valid and what i have to do if i want it the format as this:
{"1004":["1005","1006","1023"]","1007":["1008","1053"]}
Please help me out
If the inner-most values are all numbers and you want them as strings in the end result, you'll have to convert each number individually to a string.
You can do that with another loop over each items using .map() and either calling String() or .toString() for each number:
subMenuSelectedIdMap.forEach(function (items, key, subMenuSelectedIdMap){
jsonObjectOfMap[key] = items.map(function (item) {
return String(item); // or `return item.toString();`
});
});
Optionally, since String() only acknowledges one argument (with the other two that .map() passes being ignored), the loop over items could be shortened to:
jsonObjectOfMap[key] = items.map(String);

Robust String Split

I have a JavaScript function:
function doSomething(arg) {
var array = arg.split(',');
// etc...
}
arg is populated using jQuery's .data('myId') function.
Often, myId contains a comma separated list of integers and the code works great. However, if myId only contains a single integer, the code fails with the error
Object doesn't support property or method 'split'
Is there a compact, robust method to create the array without including if statements to handle the boundary conditions of one integer or an empty string?
attr will return a string, while data will try to parse the value and return an object with the "correct" type.
foo.attr('data-myId'); //pass this instead
You can't get around identifying an empty string without an if though. You either need to check for it, or for an array with a single empty string element.
You have two unrelated problems.
The first one is for case of empty string: Split will return a one-element array with an empty string. Just check for it and compensate.
var array;
if (arg == "") array = [];
If there is a single integer, I believe you are not getting a string from the .data(), but an actual integer; so first convert it into a string:
else array = String(arg).split(',');
Alternately, you could just avoid the jQuery magic, and access the attribute directly - all data() attributes are just attributes with data- prefixed.
.data will try to guess the type of the value based on its contents, so it becomes a number. You could use .attr, which always returns a string if it's available as an attribute. Alternatively, cast to a string:
('' + arg).split(',')
//or
String(arg).split(',')
I'm actually not sure whether one is preferred or not.
Also note that ''.split(',') returns [''] or an array with an empty string element. You can get around that with .filter(function (elem) { return elem !== ''; })
Another possible alternative is to use dataset on the element itself.

best way to append an item to a list within a JSON object?

I'm working on JavaScript and I have this JSON object:
var obj ={"name" : "objName",
"dynamicList" :[]};
and then I add some items to my list like this:
obj.dynamicList["someStringID"] = {"watever"};
It's important that I use a string as indexer for each item on my list (i didn't know this could be done until recently).
My only problem now is that whenever I ask for obj.dynamicList.lenght I get 0, unles I manually set the proper number... I was wondering if there's a better way to add items to my list?
Thanks!!
In Javascript, string index is not really an index. It's actually an attribute of the array object. You could set and get the value with the string index, but it's actually an empty array with some attributes. Not only .length, but also .sort(), .splice(), and other array function would not work. If there is a need to use array functions, I would use number as an index to make it a real item in the array.
If you have to use the string as an index, you couldn't rely on .length function. If there is no need to support IE prior to version 9, the Object.keys as suggested by #strimp099 should work. or you may have to create function to count the number of attributes for example:
function len(obj) {
var attrCount = 0;
for(var k in obj) {
attrCount++;
}
return attrCount;
}
and then call
len(obj.dynamicList);
Use the following the find the length of dynamicList object:
Object.keys(obj.dynamicList).length
To do this "the right way," you will have to make obj.dynamicList an object instead of an array; use {} instead of [] to set the initial value.
How to efficiently count the number of keys/properties of an object in JavaScript?
dynamiclist is an object, the length is not the length property you expect from an array.

Categories

Resources