First of all sorry if I have the terminology wrong, if so could you please correct me?
I am trying to loop through the following javascript array.
var pieData2 = [
{
label: 'wow',
value: 30,
color:"#F38630"
},
{
label: 'wow2',
value : 10,
color : "#E0E4CC"
},
{
label: 'wow3',
value : 100,
color : "#69D2E7"
}
];
I am trying to write the label and color into separate divs. I have tried the following concept, but have got no where.
$.each( pieData2[0], function( key, value ) {
alert( key + ": " + value );
});
The jQuery.each() function is designed to iterate over a collection, such as the elements in an array or over the properties of an object. In your case, it's iterating over an array of objects. In your code, pieData2 is your array, so you want to pass that as the first argument to $.each(). The second argument is a function that will handle each iteration, and has two parameters: index and value (though you can name them whatever you wish).
$.each(pieData2, function(index, value) {
// index will be 0, 1, 2
// value will be equivalent to pieData2[0], pieData2[1], pieData2[2]
console.log(value.label); // outputs wow, wow2, wow3
});
As has been used in another answer, you can also use the this keyword to refer to the element being looked at for that iteration, so this and value in the above code are the same.
http://jsfiddle.net/X5r8r/1119/
var pieData2 = [
{
label: 'wow',
value: 30,
color:"#F38630"
},
{
label: 'wow2',
value : 10,
color : "#E0E4CC"
},
{
label: 'wow3',
value : 100,
color : "#69D2E7"
}
];
$.each( pieData2, function( key, value ) {
alert( key + ": " + value['label'] +" value: " + value['value']);
});
each is fine, but you need to loop over pieData2 not over the first element of pieData2...
$.each( pieData2, function() {
alert( this.label + ": " + this.value );
});
http://jsfiddle.net/3anAJ/
Try this
$.each( pieData2, function(index) {
alert("label = " +pieData2[index].label+ " color = " +pieData2[index].color);
});
You do not need jQuery for this. In cases where jQuery really isn't needed, I don't really suggest it. At that point it's just kind of pointless. Use regular JS where possible, use jQuery where needed.
for (var i = 0; i < pieData2.length; i++) {
alert(pieData2[i].label + ' : ' + pieData2[i].value);
}
If you really want to use jQuery, since $.each can iterate over arrays AND objects, you can just use it to iterate over the array and alert each.
This will iterate over each object in the array and alert each key, value pair...
$.each(pieData2, function (key, obj) {
alert(obj.label + ' : ' + obj.value);
});
If you need to iterate over the array and over each object (if you do not know the length), then you can do:
for (var i = 0; i < pieData2.length; i++) {
for (var prop in pieData2[i]) {
if (pieData2[i].hasOwnProperty(prop)) {
alert(prop + ' : ' + pieData2[i][prop]);
}
}
}
or
$.each(pieData2, function(obj) {
$.each(pieData2[obj], function(key, value) {
alert(key + ' : ' + value);
});
});
Related
I want to understand one behavior from selectpicker. I'm trying load this this element with one attribute from my session:
Template.checkNotification.onRendered(function () {
var currentNotification = Session.get("currentNotification");
this.$('#symptoms1').selectpicker({
multipleSeparator: ' ',
});
this.$('#symptoms2').selectpicker({
multipleSeparator: ' ',
});
var symptoms = [];
for (var symptom of currentNotification.symptom.symptoms) {
symptoms.push('"' + symptom.name + ';;' + symptom.value + '"');
}
var symptomsSelected = symptoms.join(", ");
var test1 = ['Dor de Cabeça;;dor-de-cabeca','Náusea;;nausea'];
var test2 = "["+symptomsSelected+"]";
this.$('#symptoms1').selectpicker('val', test1);
this.$('#symptoms2').selectpicker('val', test2);
});
When I execute this code, only the element #symptom1 works and loads the proper options into the selectpicker.
How can I build an array of option to provide to selectpicker?
If you want to pass the symptoms to the selectpicker, you need to provide it as a native array. This code builds the array the original way and the new way (suitable for assigning to the val):
var currentNotification = {
symptom: {
symptoms: [
{ name: "symptom1", value: "value1" },
{ name: "symptom2", value: "value2" },
{ name: "symptom3", value: "value3" },
{ name: "symptom4", value: "value4" },
{ name: "symptom5", value: "value5" }
]
}
};
var symptoms = [];
for (var symptom of currentNotification.symptom.symptoms) {
symptoms.push('"' + symptom.name + ';;' + symptom.value + '"');
}
var symptomsSelected = symptoms.join(", ");
var test1 = "["+symptomsSelected+"]";
var test2 = $.map(currentNotification.symptom.symptoms, function(symptom) {
return symptom.name + ';;' + symptom.value;
});
console.log("test1: ", typeof test1, " value: ", test1);
console.log("test2: ", typeof test2, " value: ", test2);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
How does this work? The jQuery $.map function will process each of the symptoms from the currentNotification.symptom.symptoms array, and format them individually for use with selectpicker. Each element is formatted, but the array is left as a native Javascript array, with each element corresponding to the original currentNotification.symptom.symptoms array.
Compare the results of test1 and test2 to see the difference:
test1: string value: ["symptom1;;value1", "symptom2;;value2", "symptom3;;value3", "symptom4;;value4", "symptom5;;value5"]
test2: object value: [
"symptom1;;value1",
"symptom2;;value2",
"symptom3;;value3",
"symptom4;;value4",
"symptom5;;value5"
]
Note that in this example code, test1 is a string, which is formatted like an array. This resembles a JSON array value, not a native Javascript array value. test2 is a Javascript array suitable for use with selectpicker.
Using the $.map solution will solve your current problem and produce a proper Javascript array. Now, you can use this to set the val of the selectpicker:
this.$('#symptoms2').selectpicker('val', test2);
plunker: http://plnkr.co/edit/sjwK1e?p=preview
$scope.symptomsSelected="["+'"\My selected item is string\"'+"]"
$scope.test2 =angular.fromJson($scope.symptomsSelected);
$scope.test2=$scope.test2[0];
{{test2}}
<br>
{{symptomsSelected}}
I see there is a problem to get a String name from JSON object's name.
I need to parse this kind on JSON response from server.
var response = {
hopaopGmailsjIpW: {
GmailsjIpW_totalEmails_count: 133,
GmailsjIpW_state: 1
},
hopaopGmail4y4yu: {
Gmail4y4yu_totalEmails_count: 156,
Gmail4y4yu_state: 1
}
}
It is not an Array, but the object with inner objects.
i need to parse an inner ojects name and add additional values to each object.
i want be able to do something like this:
for(var i =0; i < response.length; i++){
response[i].username = parseUsernameFromString(response[i]);
response[i].service = parseServiceFromString(response[i]);
response[i].id = parseIdString(response[i]);
}
(and also state for each task)
So the question is:
What is the best way to make it?
UPDATE
this is exactly what i have for now:
for(var key in response){
if(stringContains(response[key], "Gmail")) { response[key].service = "Gmail";}
console.log("task name: "+ response[key].service);
}
function stringContains(originalString, searchString){
if(originalString.indexOf(searchString) > -1){
return true
}
else return false;
}
For walking through Objects, you need to use for ... in loop.
The real problem is: There's a , missing in your code. See the fixed working snippet:
Snippet
var response_Parsed = {
hopaopGmailsjIpW: {
GmailsjIpW_totalEmails_count: 133,
GmailsjIpW_state: 1,
service: 'Gmail',
username: 'hopaop',
id: 'sjIpW'
},
hopaopGmail4y4yu: {
Gmail4y4yu_totalEmails_count: 156,
Gmail4y4yu_state: 1,
service: 'Gmail',
username: 'hopaop',
id: '4y4yu'
}
};
for (id in response_Parsed) {
console.log("----");
if (id.indexOf("Gmail") > -1) {
console.log("We have Gmail: " + id);
console.log("UniqueName: " + id.replace("hopaopGmail", ""));
console.log("Username: " + response_Parsed[id].username);
console.log("Email Count: " + response_Parsed[id][id.replace("hopaop", "") + "_totalEmails_count"]);
}
else
console.log("We don't have Gmail: " + id);
}
And also the right way to enumerate the through the keys of the objects, is by using Object.keys.
If the response is a String like you wrote, you should first parse the JSON-String into an Object (if you're using a library like jQuery, it's probably already a JSON, as this conversion is done by jQuery automatically):
var obj = JSON.parse(responseString);
Afterwards you may iterate through it like posted above:
for (var key in obj) {
console.log("key", key, "value", obj[key]);
}
I have a REST backend link mywebsite/guests, which returns list of guests. In the front end, I want to display the guests as links. Here's the code
for(guest of guests) {
$('#guest_list').append('<a onclick="showGuest(' + guest.id + ')">' + guest.name + '</a><br>')
}
function showGuest(id) {
console.log(id)
...
}
I should mention that guest.id is a string.
The console always print undefined. My question, how can I add these links with String parameters?
for(guest of guests) {
$('#guest_list').append('<a onclick="showGuest(this)" data-id='+guest.id+'>' + guest.name + '</a><br>')
}
function showGuest(this) {
console.log($(this).data('id'))
}
The main issue is that you are trying to access the property of dynamically bound DOM elements in your showGuest(id) function. You should use the onClick function in the following way-
var guests = [{"id":1, "name":"John Doe"},
{"id":2, "name":"David Jones"}];
for(guest of guests) {
$('#guest_list').append('<a class="guest" data-id="'+guest.id+'">' + guest.name + '</a><br>');
}
$('#guest_list').on('click', 'a.guest', function() {
var id = $(this).attr('data-id');
$('.message').text('').append("Clicked guest with ID: "+id);
});
Working JSFiddle here - https://jsfiddle.net/2dkpsve8/
Hope this helps!
The way to approach this problem depends on the format and content of the guests variable. If you started with this object:
var guests = {
'123': {id: 123, name: 'joe'},
'234': {id: 234, name: 'jane'}
};
Then key would be "123" and "234" in the following loop, and the object values would be guests[key]:
for(var key in guests) {
$('#guest_list').append('<a onclick="showGuest(' + guests[key].id + ')">' + guests[key].name + '</a><br>')
}
function showGuest(id) {
console.log(id)
...
}
But if you're already using jQuery, take a look at jQuery.each for another looping option.
On the other hand, if guests is an array, as in:
var guests = [
{id:"123", name:"joe"},
{id:"234", name:"jane"}
];
then you will just want to use something like:
for(var i=0; i < guests.length; i++) {
// id is guests[i].id
// name is guests[i].name
}
Amazingly,
$('#guest_list').append('<a onclick="showGuest(' + "guest.id" + ')">' + guest.name + '</a><br>')
works fine! I don't know way. "guest.id" is replaced by the actual id of guest.
So, I'm not sure if there is a better method of what I'm trying to do, but effectively I have an array of about 12,000 elements, and each has a key in the format of:
var arrayObj = {
"blue": 'key1',
"orange": 'key2',
"red": 'key3',
"black": 'key4',
//ect...
}
I have a textbox and using javascript each keypress should check for new results. I'd like to display the top 5 most relevant results from the array based off of what is typed within the textbox. Example, if I type bl the results should be blue and black etc.
$('#searchBox').keypress(function() {
madeSearch();
}
function madeSearch() {
var isInArray = [];
if($.inArray($('#searchBox').value, arrayObj) > -1) {
//get arrayObj entry and key.
}
}
I'm just quite confused because I've never worked with javascript array keys before and I'm not sure how to attain them and what the best practices are for searching through an array of length 12,000...
Any tips or help? Thanks.
I'm not sure if this what you looking for you can use it in local by providing your array or ajax
https://github.com/devbridge/jQuery-Autocomplete
Ajax lookup:
$('#autocomplete').autocomplete({
serviceUrl: '/autocomplete/countries',
onSelect: function (suggestion) {
alert('You selected: ' + suggestion.value + ', ' + suggestion.data);
}
});
Local lookup (no ajax):
var countries = [
{ value: 'Andorra', data: 'AD' },
// ...
{ value: 'Zimbabwe', data: 'ZZ' }
];
$('#autocomplete').autocomplete({
lookup: countries,
onSelect: function (suggestion) {
alert('You selected: ' + suggestion.value + ', ' + suggestion.data);
}
});
To get the keys:
Object.keys(arrayObj)
To perform prefix search in the above key list,
Object.keys(arrayObj).filter(function(key){ return key.substring(0, input.length) === input })
If you want to optimise this further, look into data structures like Trie.
JavaScript Trie Performance Analysis
SITUATION:
I have dynamic json object data and need to use it to find element.
Example:
[
{ "tag": "article",
"id": "post-316",
"order": "0" },
{ "tag": "div",
"class": "entry-content",
"order": "0" }
]
Its length, keys and values can change anytime based on user request.
I need to use that data to dynamically find the specified element in a web page. The first set of strings will be the data for parent element, which will be used to initialize the search, and the last one will be the target children.
PURPOSE:
So, from json example above, I want to find an element with:
class name entry-content, tag name div, index 0 inside of parent with id post-316
by converting that json data in such kind of format or may be simpler and or better:
// because the parent already have attribute id, so no need to check other info of this element
var elem = $("#post-316").find(".entry-content");
if(elem.prop("tagName") == "div" ) {
elem.css("background", "#990000");
}
PROGRESS:
I tried using jquery $.each() method but can't discover myself the way to achieve that purpose.
Here is the code where I currently stuck on:
var json = $.parseJSON(theJSONData);
$.each(json, function(i, e){
$.each(e, function(key, data){
alert(i + " " + key + " " + data);
if(json.length - i == 1) {
alert("target " + data);
}
if(json.length - i == json.length) {
alert("parent " + data);
}
}
);
});
QUESTIONS:
Is it possible to achieve the PURPOSE from that kind of JSON data using iteration?
If it is possible, how to do it?
If not, what the way I can use?
You can use a format so the script knows what to get:
var data = {
'id': '#',
'class': '.'
};
var json = JSON.parse(theJSONData);
$.each(json, function (a) {
$.each(data, function (b) {
if (a[b]) {
$(data[b] + a[b])[+a['order']]; // Element
}
});
});
If you are sure about the data you are getting (As in it is class, or data, and it will have a tag name):
var json = JSON.parse(theJSONData),
last = document;
$.each(json, function (a) {
var selector = (a['id']) ? '#'+a['id'] : '.'+a['class'];
last = $(last).find(a['tag']+selector)[+a['order']]; // Element
});