Can you convert a string to the name of an array? - javascript

I'm trying to take the input from someone, commandName.substring(7) and immediately put context['display-name'] into the array which matches the name of the input.
var pokemon = [];
var Grookey = [];
pokemon.push(Grookey);
var Thwackey = [];
pokemon.push(Thwackey);
var Rillaboom = [];
pokemon.push(Rillaboom);
function addPokemon () {
var adding = commandName.substring(7);
adding.push(context['display-name']);
}
Is there any way of doing this besides
if (commandName.substring(7) === "Grookey"){
pokemon[0].push(context['display-name']);
}
This is being used for twitch chat where context['display-name'] is the user's #. For example, !trade Grookey would cause pokemon[[Phalanx],[],[]] to happen.

Use a dictionary (object):
var pokemon = {
'Grookey': [],
'Thwackey': [],
'Rillaboom': []
};
function addPokemon () {
var adding = commandName.substring(7);
// adding might be Grookey, Thwackey or Rillaboom...
pokemon[adding].push(context['display-name']);
}

Can you explain why you need use array of array? Let's try use object like this
const pokemon = {
Grookey: [],
Thwackey: [],
Rillaboom: []
}
and then
pokemon[commandName].push(context['display-name']);

Related

can't get data form array

I try to get data from the array but I get undefined
please check the image of my problem
I don't know what I'm missing
please help
I have an array called nameTable of string
when I console.log(this.nameTable) I got this : check the image please
enter image description here
and when I click to arrow I got this : check image please
enter image description here
the problem is the table has 5 element I want to show them so I make for loop to do that
for (let i = 0; i < 5; i++){
console.log(this.nameTable[i])
}
but us you can see in the image I got undefined
enter image description here
here the code :
employeeL:Array<Awinjard> = [];
inv_agentTab: Array<Inv_agent> = [];
drafbiesTab: Array<Drafbies> = [];
nameemployee: string = "";
inv_agentNombre: number = 0;
matriculeTable: Array<number> = [];
nameTable:Array<string> = [];
validatationTable: Array<number> = [];
ngOnInit() {
this.folder = this.activatedRoute.snapshot.paramMap.get('id');
this.awinjard.getAwinjardMatricule().subscribe(res => {
this.inv_agentTab = res as Array<Inv_agent>
this.inv_agentTab.forEach(element => {
this.matriculeTable[this.inv_agentNombre] = element.AGENT;
this.validatationTable[this.inv_agentNombre] = element.VLD;
this.inv_agentNombre++;
this.awinjard.getAwinjardNameAr().subscribe(res2 => {
this.drafbiesTab = res2 as Array<Drafbies>
this.drafbiesTab=this.drafbiesTab.filter((employee)=>employee.DECAFFE==element.AGENT)
this.nameemployee = this.drafbiesTab[0].AR_DELAFFE;
this.nameTable.push(this.nameemployee);
})
});
for (let i = 0; i < 5; i++){
// here the problem I can't get the data form nameTable array
console.log(this.nameTable[i])
let awin= <Awinjard> {
matricule: this.matriculeTable[i],
fullname: this.nameTable[i],
status: true,
done: 1,
mustBeDone:40
}
this.employeeL.push(awin);
}
})
}
You have subscribed to getAwinjardNameAr and before that response, you are trying to access the nameTable array, which is why you get undefined. #raishav-hanspal's solution is right to solve your issue, but a code change can keep things straightforward. I suggest you to write that code inside your for loop inside your subscribe. Here's the alteration:
this.awinjard.getAwinjardNameAr().subscribe(res2 => {
this.drafbiesTab = res2 as Array<Drafbies>
this.drafbiesTab=this.drafbiesTab.filter((employee)=>employee.DECAFFE==element.AGENT)
this.nameemployee = this.drafbiesTab[0].AR_DELAFFE;
this.nameTable.push(this.nameemployee);
let awin= <Awinjard> {
matricule: this.matriculeTable[this.inv_agentNombre],
fullname: this.nameemployee,
status: true,
done: 1,
mustBeDone:40
}
this.employeeL.push(awin);
})
You can move the code where you're logging nameTable[] inside the subscribe (where you are pushing the values into nameTable[]).
A complete solution is to use complete in subscribe() -->
this.awinjard.getAwinjardNameAr().subscribe(res2 => {
this.drafbiesTab = res2 as Array<Drafbies>
this.drafbiesTab=this.drafbiesTab.filter((employee)=>employee.DECAFFE==element.AGENT)
this.nameemployee = this.drafbiesTab[0].AR_DELAFFE;
this.nameTable.push(this.nameemployee);
},err => {console.log(err)}, ()=> {
for (let i = 0; i < 5; i++){
// here the problem I can't get the data form nameTable array
console.log(this.nameTable[i])}})
});
You can read more on https://angular.io/guide/observables

Pass array values as parameter to function and create json data

I have a scenario where I am passing an array of objects to a function in nodejs, but the same is failing with undefined error.
Here is what I have tried :
var object = issues.issues //json data
var outarr=[];
for(var key in object){
outarr.push(object[key].key)
}
console.log(outarr) // array is formed like this : ['a','b','c','d','e']
for(var i =0; i<outarr.length;i++){
jira.findIssue(outarr[i]) //here I am trying to pass the array objects into the loop one by one
.then(function(issue) {
var issue_number = issue.key
var ape = issue.fields.customfield_11442[0].value
var description = issue.fields.summary
var ice = issue.fields.customfield_15890[0].value
var vice = issue.fields.customfield_15891.value
var sor = issue.fields.labels
if (sor.indexOf("testcng") > -1) {
var val = 'yes'
} else {
var val = 'yes'
}
var obj = {};
obj['ape_n'] = ape;
obj['description_n'] = description;
obj['ice_n'] = ice;
obj['vice_n'] = vice;
obj['sor_n'] = val;
var out = {}
var key = item;
out[key] = [];
out[key].push(obj);
console.log(out)
} })
.catch(function(err) {
console.error(err);
});
});
What I am trying to achieve : I want to pass the array values as a parameter which is required by jira.findissue(bassically passing the issue number) one by one and which should again fetch the values and give a combine json output.
How can I pass this array values one by one in this function and also run jira.findissue in loop.
Any help will be great !! :-)
I have taken a look at the code in your question.
To be honest the code you wrote is messy and contains some simple syntax errors.
A good tip is to use a linter to avoid those mistakes.
More info about linters here: https://www.codereadability.com/what-are-javascript-linters/
To output all results in one array you have to define the array outside the scope of the loop.
I cleaned the code a bit up and use some es6 features. I don't know the context of the code but this is what I can make off it:
//map every value the key to outarr
let outarr = issues.issues.map( elm => elm.key);
//Output defined outside the scope of the loop
let output = [];
//looping outarr
outarr.forEach( el => {
jira.findIssue(el).then(issue => {
//creating the issue object
let obj = {
ape_n: issue.fields.customfield_11442[0].value,
description_n: issue.fields.summary,
ice_n: issue.fields.customfield_15890[0].value,
vice_n: issue.fields.customfield_15891.value,
sor_n: issue.fields.labels.indexOf("testcng") > -1 ? "yes" : "yes",
};
//pushing to the output
output[issue.key] = obj;
}).catch(err => {
console.log(err);
});
});
//ouputing the output
console.log(output);
Some more info about es6 features: https://webapplog.com/es6/

How to update JavaScript array dynamically

I have an empty javascript array(matrix) that I created to achieve refresh of divs. I created a function to dynamically put data in it. Then I created a function to update the Array (which I have issues).
The Data populated in the Array are data attributes that I put in a JSON file.
To better undertand, here are my data attributes which i put in json file:
var currentAge = $(this).data("age");
var currentDate = $(this).data("date");
var currentFullName = $(this).data("fullname");
var currentIDPerson = $(this).data("idPerson");
var currentGender = $(this).data("gender");
Creation of the array:
var arrayData = [];
Here is the function a created to initiate and addind element to the Array :
function initMatrix(p_currentIDPerson, p_currentGender, p_currentFullName, p_currentDate, p_currentAge) {
var isFound = false;
// search if the unique index match the ID of the HTML one
for (var i = 0; i < arrayData.length; i++) {
if(arrayData[i].idPerson== p_currentIDPerson) {
isFound = true;
}
}
// If it doesn't exist we add elements
if(isFound == false) {
var tempArray = [
{
currentIDPerson: p_currentIDPerson,
currentGender: p_currentGender,
currentFullName: p_currentFullName,
currentDate: p_currentDate, currentAge: p_currentAge
}
];
arrayData.push(tempArray);
}
}
The update function here is what I tried, but it doesn't work, maybe I'm not coding it the right way. If you can help please.
function updateMatrix(p_currentIDPerson, p_currentGender, p_currentFullName, p_currentDate, p_currentAge) {
for (var i = 0; i < arguments.length; i++) {
for (var key in arguments[i]) {
arrayData[i] = arguments[i][key];
}
}
}
To understand the '$this' and elm: elm is the clickableDivs where I put click event:
(function( $ ) {
// Plugin to manage clickable divs
$.fn.infoClickable = function() {
this.each(function() {
var elm = $( this );
//Call init function
initMatrixRefresh(elm.attr("idPerson"), elm.data("gender"), elm.data("fullname"), elm.data("date"), elm.data("age"));
//call function update
updateMatrix("idTest", "Alarme", "none", "10-02-17 08:20", 10);
// Définition de l'evenement click
elm.on("click", function(){});
});
}
$('.clickableDiv').infoClickable();
}( jQuery ));
Thank you in advance
Well... I would recommend you to use an object in which each key is a person id for keeping this list, instead of an array. This way you can write cleaner code that achieves the same results but with improved performance. For example:
var myDataCollection = {};
function initMatrix(p_currentIDPerson, p_currentGender, p_currentFullName, p_currentDate, p_currentAge) {
if (!myDataCollection[p_currentIDPerson]) {
myDataCollection[p_currentIDPerson] = {
currentIDPerson: p_currentIDPerson,
currentGender: p_currentGender,
currentFullName: p_currentFullName,
currentDate: p_currentDate,
currentAge: p_currentAge
};
}
}
function updateMatrix(p_currentIDPerson, p_currentGender, p_currentFullName, p_currentDate, p_currentAge) {
if (myDataCollection[p_currentIDPerson]) {
myDataCollection[p_currentIDPerson] = {
currentGender: p_currentGender,
currentFullName: p_currentFullName,
currentDate: p_currentDate,
currentAge: p_currentAge
};
}
}
Depending on your business logic, you can remove the if statements and keep only one function that adds the object when there is no object with the specified id and updates the object when there is one.
I think the shape of the resulting matrix is different than you think. Specifically, the matrix after init looks like [ [ {id, ...} ] ]. Your update function isn't looping enough. It seems like you are trying to create a data structure for storing and updating a list of users. I would recommend a flat list or an object indexed by userID since thats your lookup.
var userStorage = {}
// add/update users
userStorage[id] = {id:u_id};
// list of users
var users = Object.keys(users);

Alternative to Map.set(key, list) always points to the same list

The following code is supposed to build a map that contains (id, domainList), as the current JS version doesn't allow Map.set() (it doesn't even recognize Map()).
When using testMap[key] = domainList, it always points to the same domainList rather than other lists like Map.set() does. It always points to a single domainList.
What would be the cause of this?
testMap = {};
for (var key in idSet) {
iterator = data.iterator();
var domainList = [];
while (iterator.hasNext()) {
var tuple = iterator.next();
var domain = tuple["Domain"];
var current_Id = tuple["Id"];
if (current_Id == key) {
domainList.push(domain);
}
}
testMap[key] = domainList;
domainList.lengh() = 0;

Update collection object using Underscore / Lo-dash

I have two collections of objects. I iterate trough collection A and I want when ObjectId from A matches ObjectId from B, to update that Object in collection B.
Here is what I got so far:
var exerciseIds = _(queryItems).pluck('ExerciseId').uniq().valueOf();
var item = { Exercise: null, ExerciseCategories: [] };
var exerciseAndCategories = [];
//this part works fine
_.forEach(exerciseIds, function(id) {
var temp = _.findWhere(queryItems, { 'ExerciseId': id });
item.Exercise = temp.Exercise;
exerciseAndCategories.push(item);
});
//this is problem
_.forEach(queryItems, function (i) {
_(exerciseAndCategories).where({ 'ExerciseId': i.ExerciseId }).tap(function (x) {
x.ExerciseCategories.push(i.ExerciseCategory);
}).valueOf();
});
EDIT
Link to a Fiddle
Give this a try:
var exerciseIds = _(queryItems).pluck('ExerciseId').uniq().valueOf();
var item = {
Exercise: null,
ExerciseCategories: []
};
var exerciseAndCategories = [];
//this part works fine
_.forEach(exerciseIds, function (id) {
var temp = _.findWhere(queryItems, {
'ExerciseId': id
});
var newItem = _.clone(item);
newItem.Exercise = temp.ExerciseId;
exerciseAndCategories.push(newItem);
});
//this is problem
_.forEach(queryItems, function (i) {
_(exerciseAndCategories).where({
'Exercise': i.ExerciseId
}).tap(function (x) {
return _.forEach(x, function(item) {
item.ExerciseCategories.push(i.ExerciseCategory);
});
}).valueOf();
});
// exerciseAndCategories = [{"Exercise":1,"ExerciseCategories":["biking","cardio"]},{"Exercise":2,"ExerciseCategories":["biking","cardio"]}]
Main problem was that tap returns the array, not each item, so you have to use _.forEach within that.
FIDDLE

Categories

Resources