Storin a variable with many id's in array - javascript

var arrayOfId[] = $scope.rep.Selected.id;
I have this code. My question is if I had a some id's in $scope...Selected.id and then I make this (code) all these id's will be in every other array or in one array?

$scope.delIt = function () {
if ($scope.rep.Selected > 0) {
$scope.rep.Selected = true;
} else {
$scope.rep.Selected = false
}
var arrayOfId [] = $scope.rep.Selected.id;
for(i=0; i<=arrayOfId[i]; i++){
$http.delete("http://localhost:3000/users/" +arrayOfId[]);
}
}
This is full code. I wanted to send request every single id wich is stored in $scope.rep.Selected.id

Related

JavaScript Obj.length method returns undefined despite dictionary containing elements

I've been working on a project and I'm currently working on a function which dynamically creates a dictionary data structure. The key used is the roll number of the student, and the value is the student's name.
But I'm unable to iterate through this dictionary. I've tried displaying the dictionary on console, but all I could see is an empty dictionary. I could see the elements in it, only if I expand it further. And when I display length using Obj.length on console, it displays 'undefined'. I've read on other questions that Obj.length only works on arrays(i.e., enumerable types), and I've tried using an array instead of a dictionary. In that case, it shows an empty array and would not show values unless I manually expand it. I've also tried Obj.keys() method on the dictionary, and I've encountered the same issue.
This is the function's code:
function dictGenerator(rollnos, selectedValue) {
var dict = {};
for(let i = 0; i < rollnos.length; i++) {
get(child(dbref, "RegisterNos/" + rollnos[i])).then((snapshot)=>{
if(Object.keys(snapshot.val()).length-1 == selectedValue){
dict[rollnos[i]] = snapshot.val()["name"];
}
});
}
console.log(dict);
console.log(dict.length);
}
}
Any help on how I could iterate through my dictionary would be appreciated, Thank you.
Edit:
code implementation using promises.
function dictGenerator(regnos, selectedValue) {
const get_dict = async () => {
var dict = {};
for(let i = 0; i < regnos.length; i++){
get(child(dbref, "RegisterNos/" + regnos[i])).then((snapshot)=>{
if(Object.keys(snapshot.val()).length-1 == selectedValue){
dict[regnos[i]] = snapshot.val()["name"];
}
});
}
return dict;
};
get_dict().then((dict) => {
console.log(dict);
});
}
Basing on comments made by VALZ and JaredSmith, this is the working code:
function dictGenerator(regnos, selectedValue) {
const get_dict = async () => {
var dict = {};
for(let i = 0; i < regnos.length; i++){
await get(child(dbref, "RegisterNos/" + regnos[i])).then((snapshot)=>{
if(Object.keys(snapshot.val()).length-1 == selectedValue){
dict[regnos[i]] = snapshot.val()["name"];
}
});
}
return dict;
};
get_dict().then((dict) => {
console.log(dict);
});
}
}

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);

Overwrite/Replace Value in multi-dimensional array

So I am currently trying to overwrite a value in my multidimensional array.....where I want to overwrite a value based on the position of where channel.name is and change the value of the mute state if you will.
So what I want to do is:
Mute value in array
When I call the function to unmute it, I want to replace the "Mute" Value with "Unmute".
Then do the same Mute and effectively toggle values.
The problem is I am currently always pushing the values on over and over like so: [ [ '1447682617.29', 'SIP/487-0000000b', 'Mute', 'Unmute' ] ]
I simply just want to overwrite Mute and Replace it with Unmute.
I have the index part fine its just being able to overwrite that value.
The code I have so far is:
//ARI function to mute channels.
function mute(mutval,mutestate) {
console.log("Muting:" + mutval);
var index = 0;
var findex = false;
for (var i in channelArr) {
var channelArrEle = channelArr[i];
if (channelArrEle[0] == mutval) {
index = i;
findex = true;
console.log("First Part works!")
}
}
if (findex) {
channelArr[index].push(mutestate);
console.log(channelArr);
} else {
console.log("Error")
}
}
//ARI function to unmute channels which have been muted.
function unmute(unval,mutestate) {
console.log("Unmuting: " + unval);
var index = 0;
var findex = false;
for (var i in channelArr) {
var channelArrEle = channelArr[i];
if (channelArrEle[0] == unval) {
index = i;
findex = true;
console.log("First Part works!")
}
}
if (findex) {
channelArr[index].push(mutestate);
//Just added this to see what would happen!
channelArr[index] = mutestate;
console.log(channelArr);
} else {
console.log("Error")
}
}
Any suggestions no doubt its something minor question is what.
Try change (in both occurence)
channelArr[index].push(mutestate);
with
var channelData = channelArr[index];
channelData[2] = mutestate;
channelArr[index] = channelData;
And if it works, you can try to shorten the code like this
channelArr[index][2] = mutestate;

Access js array in another js file

I fill my array in the checklistRequest.js and I want to access it in my Termine_1s.html file which contains js code. I can access it but when I want to iterate through it, it gives me only single digits instead of the strings.
How can I solve this?
checklistRequest.js
//Calls the checkbox values
function alertFunction()
{
//Retrieve the object from storage
var retrievedObject = localStorage.getItem('checkboxArray');
console.log('retrievedObject: ', JSON.parse(retrievedObject));
return retrievedObject;
}
Termine_1s.html
//Checks if title was checked already
var checklistRequest = alertFunction();
var titleAccepted = true;
for (var a = 0; a < checklistRequest.length; a++)//Iterates through whole array
{
if(title != checklistRequest[i] && titleAccepted == true)//Stops if false
{
titleAccepted = true;
}
else
{
titleAccepted = false;
}
}
you need to parse the object at some point.
Try:
return JSON.parse(retrievedObject);

Advanced search/queue array collection question

I have a pretty large number of objects "usrSession" I store them in my ArrayCollection usrSessionCollection.
I'M looking for a function that returns the latest userSessions added with a unique userID. So something like this:
1.
search the usrSessionCollection and only return one userSessions per userID.
2.
When it has returned x number of userSessions then deleted them from the usrSessionCollection
I'M stuck - would really love some code that can help me with that.
function ArrayCollection() {
var myArray = new Array;
return {
empty: function () {
myArray.splice(0, myArray.length);
},
add: function (myElement) {
myArray.push(myElement);
}
}
}
function usrSession(userID, cords, color) {
this.UserID = userID;
this.Cords = cords;
this.Color = color;
}
usrSessionCollection = new ArrayCollection();
$.getJSON(dataurl, function (data) {
for (var x = 0; x < data.length; x++) {
usrSessionCollection.add(new usrSession(data[x].usrID.toString(), data[x].usrcords.toString() ,data[x].color.toString());
}
});
Thanks.
The biggest issue is that you have made the array private to the outside world. Only methods through which the array can be interacted with are add and empty. To be able to search the array, you need to either add that functionality in the returned object, or expose the array. Here is a modified ArrayCollection:
function ArrayCollection() {
var myArray = new Array;
return {
empty: function () {
myArray.splice(0, myArray.length);
},
add: function (myElement) {
myArray.push(myElement);
},
getAll: function() {
return myArray;
}
}
}
Now to get the last N unique session objects in usrSessionCollection, traverse the sessions array backwards. Maintain a hash of all userID's seen so far, so if a repeated userID comes along, that can be ignored. Once you've collected N such user sessions or reached the beginning of the array, return all collected sessions.
usrSessionCollection.getLast = function(n) {
var sessions = this.getAll();
var uniqueSessions = [];
var addedUserIDs = {}, session, count, userID;
for(var i = sessions.length - 1; i >= 0, uniqueSessions.length < n; i--) {
session = sessions[i];
userID = session.userID;
if(!addedUserIDs[userID]) {
uniqueSessions.push(session);
addedUserIDs[userID] = true;
}
}
return uniqueSessions;
}
I wouldn't combine the delete step with the traversal step, just to keep things simple. So here's the remove method that removes the given session from the array. Again, it's better to modify the interface returned by ArrayCollection rather than tampering with the sessions array directly.
function ArrayCollection(..) {
return {
..,
remove: function(item) {
for(var i = 0; i < myArray.length; i++) {
if(item == myArray[i]) {
return myArray.splice(i, 1);
}
}
return null;
}
};
}
Example: Get the last 10 unique sessions and delete them:
var sessions = usrSessionCollection.getLast(10);
for(var i = 0; i < sessions.length; i++) {
console.log(sessions[i].UserID); // don't need dummy variable, log directly
usrSessionCollection.remove(sessions[i]);
}
See a working example.
You made your array private, so you can't access the data, except adding a new element or removing them all. You need to make the array public, or provide a public interface to access the data. Like first(), next() or item(index).
Then you can add a search(userID) method to the usrSessionCollection, which uses this interface to go through the elements and search by userID.
UPDATE: this is how I would do it: - See it in action. (click preview)
// user session
function userSession(userID, cords, color) {
this.UserID = userID;
this.Cords = cords;
this.Color = color;
}
// a collection of user sessionions
// a decorated array basically, with
// tons of great methods available
var userSessionCollection = Array;
userSessionCollection.prototype.lastById = function( userID ) {
for ( var i = this.length; i--; ) {
if ( this[i].UserID === userID ) {
return this[i];
}
}
// NOTE: returns undefined by default
// which is good. means: no match
};
// we can have aliases for basic functions
userSessionCollection.prototype.add = Array.prototype.push;
// or make new ones
userSessionCollection.prototype.empty = function() {
return this.splice(0, this.length);
};
//////////////////////////////////////////////////////
// make a new collection
var coll = new userSessionCollection();
// put elements in (push and add are also available)
coll.add ( new userSession(134, [112, 443], "#fffff") );
coll.push( new userSession(23, [32, -32], "#fe233") );
coll.push( new userSession(324, [1, 53], "#ddddd") );
// search by id (custom method)
var search = coll.lastById(134);
if( search ) {
console.log(search.UserID);
} else {
console.log("there is no match");
}
// empty and search again
coll.empty();
search = coll.lastById(134);
if( search ) {
console.log(search.UserID);
} else {
console.log("there is no match");
}

Categories

Resources