Say this is my json
[
{
"imageSmall": ["images/employee_jpgs/employees_abhishek_80x80.jpg"],
"imageBig": ["images/employee_jpgs/employees_abhishek_150x150.jpg"],
"name": ["Abhishek Shet"],
"quotes": ["Just perfect to start your career after school. Makes me feel others in the industry are way slower then us. Awesome team and and a brilliant product to work on!!!!. And most importantly I enjoy what I do :)."],
"type": "employee"
},
{
"imageSmall": ["images/employee_jpgs/employees_barbra_80x80.jpg"],
"imageBig": ["images/employee_jpgs/employees_barbra_150x150.jpg"],
"name": ["Barbra Gago"],
"quotes": ["The best part about working at tibbr is how dynamic the environment is, there's a lot of flexibility and freedom to execute on new ideas. Because everyone is so talented, there is a ton of trust and support coming from managers and team members-we all count on each other to do the best possible job!"],
"type": "employee"
},
the same continues but there are 3 types
1-employee
2-twitter
3-social
Now my problem is I want get these json data randomly and append to my div element
I used following code
function(args){
var me=this;
$.getJSON(args.json,function(data) {
me.set(args);
$.each(data, function(i){
var id="randomizr_item_" + i;
var temp= $('<div id='+ id +' class="randomizr-grid-items"><img src="'+ this.imageSmall[0] +'" /></div>');
me.config.container.append(temp);
this.target=$(temp);
});
I know how to generate single random entry using following code
entry = data[Math.floor(Math.random()*data.length)];
which generates single random entry.
Plz help me how to get json data randomly from above json file and append to div.
You need to make an array of random unique numbers like following:
function generateRandom(min, max) {
var arr = [];
while(arr.length < 5){
var randNum = Math.floor(Math.random() * (max - min + 1)) + min,
found=false;
for(var i=0;i < arr.length; i++){
if(arr[i] == randNum){found=true;break}
}
if(!found)arr[arr.length] = randNum;
}
return arr;
}
Then you need to loop over data like following:
Here I am looping over unique array, not on data and using value of array as index to data.
var orders = generateRandom(0, data.length-1);
$.each(orders, function(index, value){
var id="randomizr_item_" + i;
var temp= $('<div id='+ id +' class="randomizr-grid-items"><img src="'+ data[value].imageSmall[0] +'" /></div>');
me.config.container.append(temp);
this.target=$(temp);
});
A simple demo
You should create a 'Deck' and fill it with the json data.
Once the Deck is filled, loop through it while it has elements, like this:
while(deck.length > 0) {
var random_index = Math.floor(Math.random()*data.length);
var item = deck[random_index];
// do stuff with item
deck = jQuery.removeFromArray(random_index, deck);
}
Add this code to the top of your js file:
jQuery.removeFromArray = function(value, arr) {
return jQuery.grep(arr, function(elem, index) {
return elem !== value;
});
};
Related
My server(PHP) response JSON object like this data:
{
"0": {
"action_id": "80",
"action_transaction_id": "5743",
"action_matched_email": "test_1#gmail.com",
"action_by_user": "user1",
"action_count": "0",
"action_date": "2017-07-19 15:01:26"
},
"1": {
"action_id": "1",
"action_transaction_id": "1",
"action_matched_email": "Admin#email.com",
"action_by_user": "ADMIN",
"action_count": "4",
"action_date": "2017-07-19 15:10:08"
},
"new_count": {
"action_count": "4"
}
}
The data are not limited, sometimes server throws many data. It depends on what the condition is.
This is my ajax did after success:
success: function(data, status, jqXHR) {
$.each(data, function(i, row) {
document.getElementById("hidden_counter").value = "";//new_count value here
var allRows =window.parent.document.getElementsByClassName('row'+row.action_transaction_id+'');
for (var i = 0; i < allRows.length; i++) {
allRows[i].style.backgroundColor = '#008e00';
allRows[i].style.color = '#f0fff0';
//should exclude the last array when updating the bgcolor and style color of the row
}
});
}
I have 2 things to know and do.
How can I get the last object?
"new_count": {
"action_count": "4"
}
so that I can update my hidden input value to it.
How can I exclude the last object when updating the styles of rows?
You shouldn't mixup pure js with jquery:
success: function(data, status, jqXHR) {
$('#hidden_counter').val(data.new_count.action_count);
$.each(data, function(i, row) {
if (row.action_transaction_id === undefined) {
return;
}
$('.row' + row.action_transaction_id).css({
backgroundColor: '#008e00',
color: '#f0fff0'
});
});
}
If your object name is lets say jsondata then for accesing new_count you can get it using,
jsondata.new_count
If you want to access last element then you can access it through ,
jsondata.new_count.action_count
How can I get the last object?
Object keys are not sorted and are retrieved in an order specific to browsers. So you can try to do is, get list of keys and take the maximum value.
As commented before, this should do the trick:
var lastIndex = Math.max.apply(null, Object.keys(object).map(Number))
How can I exclude the last object when updating the styles of rows?
You can either stop loop at length - 1
or you can try to use CSS selectors:
var selector = '.row' + row.action_transaction_id + ':not(:last-child)';
var allRows = window.parent.document.querySelectorAll(selector);
// OR since you are using jQuery
var allRows = $(window).parent().find(selector)
// OR
var selector = '.row' + row.action_transaction_id;
var allRows = $(window).parent().find(selector).not(':last-child')
You can use Object.keys
success: function(data, status, jqXHR) {
var lastKey = Object.keys(data)[Object.keys(data).length-1];
$.each(data, function(i, row) {
if (i== lastKey) { /* It's the last key */ }
...
Note that for older browsers you may need to use the polyfill included in that link.
try this:
$.each(data, function(i, row) {
if(row["action_count"])
{
document.getElementById("hidden_counter").value = row["action_count"];
}
else
{
var allRows =window.parent.document.getElementsByClassName('row'+row.action_transaction_id+'');
for (var i = 0; i < allRows.length; i++) {
allRows[i].style.backgroundColor = '#008e00';
allRows[i].style.color = '#f0fff0';
}
}
});
first piece: get the element with greatest index (=length - 1)
second: loop all elements from index 0 until index < length-1
var lastArrayElement = allRows[allRows.length - 1];
var action_count = lastArrayElement.action_count;
// loop all but last element:
for(var i=0; i<allRows.length-1;i++){
do_something(allRows[i]); //custom function
}
assumption:
the index is correct and not resorted in the process of creating json object
the index is indeed a range from 0 to some integer, without values left out
edit
indeed the allRows.length will not work as it is an object (containing pure numeric values as properties).
Object.keys(allRows).length will give you the count van properties. However it will give you 3 as the last textual index is taken in the count as well.
var max = 0;
for(i = 0; i < Object.keys(allRows).length;i++) {
if(parseInt(Object.keys(allRows)[i]) > max) {
max = Object.keys(allRows)[i];
}
}
the last element then will be in
var lastArrayElement = allRows[max];
Been struggling with counting through this array. I was able to do it previously but I don't think I quite understand how the parameters of a function are assigned its data.
I am bringing in an array with from JSON data over AJAX, then using a .each loop to go through the data and count it. But I can't seem to count it when using the index parameter. It is just giving me the actual objects and not counting how many objects there are.
I was hoping that someone could help me understand why I am getting the object and not the count of objects in the array. What I have now is just my final attempt at getting it to count, I know it's wrong.
I am trying to count how many "results" there are in the array (that came from the JSON file).
I have added snippets of my code and attached a link to the JSON file. I have also marked the problem area with a comment saying Problem Area
CODE -
$.getJSON('http://api.fixer.io/latest?base=ZAR', {
action: "query",
list: "search",
format: "json",
}
, function (data) {
var baseCurr = data.base;
var baseDate = data.date;
$('#curr-cont').append('<div class="base row1" id="row1"><div class="base flag" id="flag"><i class="famfamfam-flag-za"></i></div><div class="base country-name"><p class="c-name" id="count-name">' + baseCurr + '</p></div><div class="base currency"><p class="c-amount" id="curr">' + baseDate + '</p></div></div>');
//***Problem Area***
var rates = [data];
$.each(rates[0], function (i, obj) {
console.log(obj);
});
$.each(data.rates, function (i, item) {
var amount = [item];
var name = [i];
var maxLength = 4;
var string = amount.toString();
string = string.substr(0, maxLength);
// amount = amount.substr(0, maxLength);
$('#curr-cont').append('<div class="row1" id="row1"><div class="flag" id="flag"><i class="famfamfam-flag-' + name + '"></i></div><div class="country-name"><p class="c-name" id="count-name">' + name + '</p></div><div class="currency"><p class="c-amount" id="curr">' + string + '</p></div></div>');
// if(i > 0){
// $('#list1').append('<li>' + name + '</li>');
// }
// else{
// $('#list2').append('<li>' + name + '</li>');
// }
});
});
JSON Data File
edit:
since rates is an object and not an array, you can do: Object.keys(data.rates).length.
Object.keys(...) will give you an array with all the keys in the object.
original:
If you want to know the number of rates in that file: data.rates.length will give you the length of the rates Array that is returned in the data.
No need to count it
I am new to js and I don't understand much of codes and conditions in js.
My question is simple but I need someone to give me a good example if possible as I know what I need but it is getting hard to implement that in code.
This is my code with 2 arrays where the data is coming from.
blind_tmp = '';
for (i=0; i<#All of Blind Relationship Link.length; i++){
blind_tmp = blind_tmp + '<p>[**' + #All of Element Title[i] + '**](' + #All of Blind Relationship Link[i] + ')'
};
What simple needed is that. I want merge records that are duplicates printed.
for example: if Blind Relationship link is AF44 and after 6 elements this AF44 comes again so I want both to be written like 1.AF44,2.AF44
while now it is writing the elements how they come along
example:
AF11,AF22,AF33,AF44,AF55,AF66,AF77,AF44
so in this example you see two AF44
I want them to be written like this
AF11,AF22,AF33,AF44AF44,AF55,AF66,AF77
any help with a code example is appreciated.
The idea is to iterate through each element in the blindRelationshipLink and store those elements in a temporary array which will be used to check the number of occurrence of an array element.
var blindRelationshipLink = ['AF11','AF22','AF33','AF11','AF44','AF44','AF55','AF66','AF77','AF11','AF22','AF11'];
var arrTemp = [];
var p = '';
blindRelationshipLink.forEach(function(arr){
var count = 0;
arrTemp.forEach(function(a){
if(arr === a)
count++;
});
arrTemp.push(arr);
if(count){
count++;
arr= arr + '.' + count;
}
p = p + arr + ',';
});
alert(p);
You test by running the code snippet.
This approach is not best but it may serve your purpose.
Here is a snippet
var elemArray = ['AF11', 'AF22', 'AF33', 'AF44', 'AF55', 'AF66', 'AF77', 'AF44']; // Array of elements
//A new array which which will contain elements which pass our case
var finalArray = [];
elemArray.forEach(function(item) { // loop through main array
// Check if element is present or else push the element
if (finalArray.indexOf(item) == -1) {
finalArray.push(item);
} else {
// if element is there find the index
var getIndex = finalArray.indexOf(item);
// remove the element, else there will be duplicate
finalArray.splice(getIndex, 1);
//concate the matched element
var newElem = item + item;
// push the element in specfic index
finalArray[getIndex] = newElem;
}
})
console.log(finalArray)
Current drawback with this code is what will happen if there are multiple repeated item in the main array. For example presence of AF33 more than twice.
DEMO
I have to build JS multi select questionnaire.
In order to read the json details I use the following code:
$(document).ready(function(){
$.getJSON("data.json", function(json) {
var anserFor1st = json.questions[0].answers;
var anserFor2nd = json.questions[1].answers;//If it's more than two use a loop
document.getElementById("content").innerHTML = JSON.stringify(anserFor1st) + "<br/>" + JSON.stringify(anserFor2nd);
var aString = "";
Object.keys(anserFor1st).forEach(function (k) {aString += anserFor1st[k] + "<br/>";});
Object.keys(anserFor2nd).forEach(function (k) {aString += anserFor2nd[k] + "<br/>";});
document.getElementById("content").innerHTML = aString;
});
});
I have to shoe all of the questions&answers in the same page but every time with different content (aka question&answer). I have to move between questions by back and forward buttons. How do I display the values of the different question dynamically in the html?
If you have all the questions in a list, as it appears you do, the jQuery to dynamically change the question content is pretty trivial. We can create a function, and pass parameters to the function telling it to move forwards or backwards in the array of questions, as long as it doesn't extend outside the array. An example of this is here.
var testArray = ["first q", "second q", "third q", "fourth q"];
var questionIndex = 0;
function updateQuestion(direction) {
questionIndex += direction;
if (questionIndex < testArray.length && questionIndex >= 0) {
$(".question").html(testArray[questionIndex]);
} else {
questionIndex -= direction;
}
}
$(document).ready(function () {
updateQuestion(0);
});
You should be able to loop through your questions and append the JSON data to a blank array in place of testArray.
i have this json data and i want to get length of this json data and also of css
my json data is shown here
jso({tag:"div",css:{backgroundColor:"red"},html:"abc"})
i have pass this in function
function jso(data){
alert(data.length)
}
Your JSON is not a valid JSON object
{
"tag": "div",
"css": {
"backgroundColor":"red"
},
"html":"abc"
}
However proper JSON object don't have a length attribute, so you need to iterate over them to calculate the length.
i know what u mean u just need to loop over your object with a counter variable
var x = {tag:"div",css:{backgroundColor:"red"},html:"abc"}
function objectLength(obj){
var counter = 0;
for(var i in obj)
{
counter +=1;
}
return counter
}
use it like this
alert(objectLength(x))
To iterate over the data using jQuery counting how many iterations you did do the following:
var data = {tag:"div",css:{backgroundColor:"red"},html:"abc"};
var count = 0;
$.each(data, function(key, value) {
count++;
});
See jsFiddle here.
To iterate over the data using JavaScript only counting how many iterations you did do the following:
var data = {tag:"div",css:{backgroundColor:"red"},html:"abc"};
var count = 0;
var key;
for(key in data)
{
var value = data[key];
count++;
}
​See jsFiddle here.