I'm trying to generate markers for every user in my $.each loop in such a way that I can select each marker using the corresponding userId of a given user.
$.each($.parseJSON(window.usersArray), function (i, user) {
window.userMarkers[user['id']] = L.marker(98.76, 12.34).addTo(map);
console.log(window.userMarkers[user['id']]);
});
EDIT
I get the error:
Cannot set property '3' of undefined, where 3 is the user's ID.
You need to create the object (or array depending on your needs) before you can add anything to it.
window.userMarkers = {};
$.each($.parseJSON(window.usersArray), function (i, user) {
window.userMarkers[user['id']] = L.marker(98.76, 12.34).addTo(map);
console.log(window.userMarkers[user['id']]);
});
Solution: Define the array before setting properties to it! Example:
window.userMarkers = new Array();
Related
Json Array Object
Through Ajax I will get dynamic data which is not constant or similar data based on query data will change. But I want to display charts so I used chartjs where I need to pass array data. So I tried below code but whenever data changes that code will break.
I cannot paste complete JSON file so after parsing it looks like this
[{"brand":"DUNKIN' DONUTS KEURIG","volume":1.9,"value":571757},{"brand":"MC CAFE","volume":1.1,"value":265096}];
You can use Object.keys and specify the position number to get that value
var valueOne =[];
var valueTwo = [];
jsonData.forEach(function(e){
valueOne.push(e[Object.keys(e)[1]]);
valueTwo.push(e[Object.keys(e)[2]]);
})
It seems like what you're trying to do is conditionally populate an array based the data you are receiving. One solution might be for you to use a variable who's value is based on whether the value or price property exist on the object. For example, in your forEach loop:
const valueOne = [];
jsonData.forEach((e) => {
const val = typeof e.value !== undefined ? e.value : e.average;
valueOne.push(val);
})
In your jsonData.forEach loop you can test existence of element by using something like:
if (e['volume']===undefined) {
valueone.push(e.price);
} else {
valueone.push(e.volume);
}
And similar for valuetwo...
You could create an object with the keys of your first array element, and values corresponding to the arrays you are after:
var data = [{"brand":"DUNKIN' DONUTS KEURIG","volume":1.9,"value":571757},{"brand":"MC CAFE","volume":1.1,"value":265096}];
var splitArrays = Object.keys(data[0]).reduce((o, e) => {
o[e] = data.map(el => el[e]);
return o;
}, {});
// show the whole object
console.log(splitArrays);
// show the individual arrays
console.log("brand");
console.log(splitArrays.brand);
console.log("volume");
console.log(splitArrays.volume);
// etc
Context
In a Firebase DB I'm storing "events" and "users". Users can have favorite events, to manage them I only store the event's id in the favorite user's DB location. So to grab favorite events informations, I need to firstable grab the event id and then go to the DB events location, to collect all the datas I need.
Problem
I would like to store in an Array all the favorite events informations (each event would be an Object with inside it : "key" : "value"), to use that Array in my HTML view and print the informations. But it doesn't work the way I coded it... :(
// This ref is too grab favorite event id (in my case only 2) in the user DB location
var refUserFavoris = firebase.database().ref().child("users/"+user.uid+"/events/favoris");
$scope.favorisTmp = $firebaseArray(refUserFavoris);
// This shows one array, with two objects (wich are my two user's favorite events) wich include ids
console.log($scope.favorisTmp);
// This is to load the objects and with the foreEach, grab there ids to use them in the next ref call
$scope.favorisTmp.$loaded().then(function()
{
angular.forEach($scope.favorisTmp, function(favoris)
{
// This shows two lines : the id of each object
console.log(favoris.$id);
// Call a new ref to reach the event informations (in a different location of the DB) using the previous id
firebase.database().ref("events/"+favoris.$id).once('value').then(function(snapshot)
{
// Attempt to store events datas for each id I have (in my case, only two)
snapshot.forEach(function(favorisSnap)
{
var favSnap = favorisSnap.val();
// This shows a lot of "undefined" lines, wich I don't want. I would like two objects, with all informations inside
console.log(favSnap.nbPersonne);
// $scope.favorisF is an Array that I would like to use in a ng-repeat to print all datas for each event
// For now this doesn't show anything
$scope.favorisF = favSnap;
});
// If using favSnap out of the previous function, I got a "favSnap" is undifined error
console.log(favSnap);
});
});
});
<ion-item ng-repeat="f in favorisF" class="item-avatar">
{{f.nbPersonne}}
</ion-item>
EDIT 1 :
I tried a new way to have my data, but a new problem came, how to fill an Array inside a loop ? I've tried "push" and "$add" methods, but no one worked. Any ideas ?
var newFav = [];
var user;
user = firebase.auth().currentUser;
var refUserFavoris = firebase.database().ref().child("users/"+user.uid+"/events/favoris");
$scope.favorisTmp = $firebaseArray(refUserFavoris);
$scope.favorisTmp.$loaded().then(function()
{
angular.forEach($scope.favorisTmp, function(favoris)
{
console.log(favoris.$id);
var refFavoris = firebase.database().ref("events/"+favoris.$id);
refFavoris.on('value', function(snap)
{
//This is where I'm trying to fill "newFav" in each steps of the loop
newFav.push(snap.val());
console.log("Scope newFav vaut :", $scope.newFav);
});
});
});
I think you made a typo here.
var refUserFavoris = firebase.database().ref("events/favoris/"+favoris.$id).once('value')
Thanks a lot Abdel, I fixed my problem :
Here is the solution
$scope.newFav = [];
console.log($scope.newFav);
$scope.favorisTmp.$loaded().then(function()
{
angular.forEach($scope.favorisTmp, function(favoris)
{
console.log(favoris.$id);
var refFavoris = firebase.database().ref("events/"+favoris.$id);
refFavoris.on('value', function(snap)
{
$scope.newFav.push(snap.val());
console.log("Scope newFav vaut :", $scope.newFav);
});
});
});
Currently I have a form with 10 fields that I need to do sendkeys > store the value and after assert this value when save the form. For each of these fields I need to create a function and store the value in a variable or is there a better way?
My actual code:
var email = driver.findElement(By.name('email'));
email.sendKeys('info#domain.com');
email.getAttribute("value").then(function(email_text) {
var email = email_text;
});
Cheers,
Rafael
If I understand correct, the process looks like you should fill some fields, remember their values and check values after the form has been submitted.
There is no one standard decision for tasks like this, it depends on developer.
So, we know which values we need and can store it for example in map
{
'email':'example#email.com',
'telephone':111222333
}
Key is name for finding element, value - for sendKey and checkValue methods.
You should write two methods, which will work with test data map and will fill inputs and check values in cycle by map keys.
Do you mean you want to do this as an array?
// you can represent each field as an object
var fields = [
{ elementName: 'email', expectedText: 'info#domain.com' },
{ elementName: 'password', expectedText: 'bla bla bla' }
];
// sendKeys to each field with the specified text
fields.forEach(function(field) {
browser.driver.findElement(by.name(field.elementName)).sendKeys(field.expectedText);
});
// to get all the field text (from promises) and store it as an array
browser.controlFlow().execute(function() {
var textArray = [];
fields.forEach(function(field) {
browser.driver.findElement(by.name(field.elementName)).getAttribute('value').then(function(actualText) {
textArray.push({elementName: field.elementName, actualText: actualText});
});
});
return textArray;
}).then(function(storedTextArray) {
// do something with the stored text array here
});
I'm creating a very simplified version of a drag and drop shopping cart with jqueryui.
My issue is regarding adding data(id, name, price) to an array.
I tried several methodes of adding the data (also an array) to the main container(array). But I keep getting this error: Uncaught TypeError: undefined is not a function
var data = [];
function addproduct(id,name,price){
//var d = [id,name,price];
data[id]["name"] = name;
data[id]["price"] = price;
data[id]["count"] = data[id]["count"]+1;
console.log(data);
}
the addproduct() function can be called by pressing a button
It is not entirely clear to me what type of data structure you want to end up with after you've added a number of items to the cart. So, this answer is a guess based on what it looks like you're trying to do in your question, but if you show a Javascript literal for what you want the actual structure to look like after there are several items in the cart, we can be sure we make the best recommendation.
You have to initialize a javascript object or array before you can use it. The usual way to do that is to check if it exists and if it does not, then initialize it before assigning to it. And, since you're keeping a count, you also will want to initialize the count.
var data = [];
function addproduct(id,name,price){
if (!data[id]) {
// initialize object and count
data[id] = {count: 0};
}
data[id]["name"] = name;
data[id]["price"] = price;
++data[id]["count"];
console.log(data);
}
And FYI, arrays are used for numeric indexes. If you're using property names like "name" and "price" to access properties, you should use an object instead of an array.
And, I would suggest that you use the dot syntax for known property strings:
var data = [];
function addproduct(id,name,price){
if (!data[id]) {
// initialize object and count
data[id] = {count: 0};
}
data[id].name = name;
data[id].price = price;
++data[id].count;
console.log(data);
}
It looks like what you want is an array of objects, although I would need a more detailed description of your problem to be clear.
var data = []
function addproduct(id, name, price)
{
data.push({'id': id, 'name':name, 'price': price, 'count': ++count});
console.log(data);
}
so I have a JSON object returned from a webservice. Now I want to:
get a subset which matches a categoryTitle i pass as parameter (this seems to work)
from my filtered resultset I want to get another array of objects (helpsubjects), and for each of this subjects I want to extract the SubjectTitle.
Problem: It seems my Array of HelpSubjects does not exist, but I can't figure out why and hope you could help.
Perhaps this piece of commented code makes it more clear:
$.fn.helpTopicMenu = function (data) {
that = this;
var categoryContent = contents.filter(function (el) {
return el.CategoryTitle == data.categoryTitle;
});
debug('categorys Content: ', categoryContent); //see below
var container = $('#subjectList');
var subjectList = categoryContent.HelpSubjects;
debug('Subjects in Category: ', subjectList); // UNDEFINED?!
$.each(subjectList, function (i, item) {
container.append(
$('<li></li>').html(subjectList[i].SubjectTitle)
);
});
the line debug('categorys Content: ', categoryContent); returns the following object as shown in the picutre (sadly I can't add a picture directly to the post yet, so here's the link): http://i.stack.imgur.com/0kKWx.png
so as I understand it, there IS actually a HelpSubjects-Array, each entry containing a SubjectTitle (in the picture there actually is only one entry, but I need to have the Artikel einfügen as my html.
Would be great if you can help me.
The variable categoryContent set is an array of objects.
Try debugging categoryContent[0].HelpSubjects and see if you can access the property. If so, you can also loop this array if need be.