For loop not working with js map function - javascript

I am trying to print array in html, but my for loop is not working. I am trying to get the length of dataArrayNew but its not returning back where my for loop is added. If i console.log(dataArrayNew.title); , I am able to see the correct result. I am also attaching the print screen of my browser console.
var dataArrayNew = [];
function fetch_section_data_1(){
var keys = Object.keys(localStorage).filter(function(key) {
return /^section\d+$/.test(key);
});
var dataArray = keys.map(function(key) {
dataArrayNew = JSON.parse(localStorage.getItem(key));
console.log(dataArrayNew.title);
//lengtharray = dataArrayNew.length;
//console.log(lengtharray);
//return JSON.parse(localStorage.getItem(key));
});
var $table = $( "<table></table>" );
for(i=0;i<dataArrayNew.length;i++){
var array_no = dataArrayNew[i];
var $line = $( "<tr></tr>" );
$line.append( $( "<td></td>" ).html( array_no.title ) );
$table.append( $line );
console.log(dataArrayNew.title);
}
$table.appendTo(document.body);
}

The reason why you cannot see the length property is because you are reassigning dataArrayNew from an array to a result JSON.parse which is an object, and objects do not have the property length. Instead of reassigning the value of dataArrayNew, why don't you push the value of JSON.parse(localStorage.getItem(key)) to it, like so:
dataArrayNew.push(JSON.parse(localStorage.getItem(key)));
So your code should look something like this:
var dataArrayNew = [];
function fetch_section_data_1(){
var keys = Object.keys(localStorage).filter(function(key) {
return /^section\d+$/.test(key);
});
var dataArray = keys.map(function(key) {
var currIn = JSON.parse(localStorage.getItem(key));
console.log(currIn);
// push data to dataArrayNew
dataArrayNew.push(currIn);
//lengtharray = dataArrayNew.length;
//console.log(lengtharray);
//return JSON.parse(localStorage.getItem(key));
});
var $table = $( "<table></table>" );
// You should be able to get the length here now
for(var i = 0; i < dataArrayNew.length; i++){
var array_no = dataArrayNew[i];
var $line = $( "<tr></tr>" );
$line.append( $( "<td></td>" ).html( array_no.title ) );
$table.append( $line );
console.log(dataArrayNew.title);
}
$table.appendTo(document.body);
}

Related

Max value from 4 json source url

I have fetch some value from json url, with this
$(document).ready(function () {
function price(){
$.getJSON('https://poloniex.com/public?command=returnTicker', function(data){
document.getElementById('PoloniexLastNXT').innerHTML = (data.BTC_NXT.last);
document.getElementById('PoloniexBidNXT').innerHTML = (data.BTC_NXT.highestBid);
document.getElementById('PoloniexAskNXT').innerHTML = (data.BTC_NXT.lowestAsk);
});
$.getJSON('trade/libs/bittrex.php?i=nxt', function(data){
document.getElementById('BittrexLastNXT').innerHTML = (data.Bittrex);
document.getElementById('BittrexBidNXT').innerHTML = (data.BittrexBid);
document.getElementById('BittrexAskNXT').innerHTML = (data.BittrexAsk);
});
$.getJSON('trade/libs/hitbtc2.php?i=NXT', function(data){
document.getElementById('HitbtcLastNXT').innerHTML = (data.hitbtc);
document.getElementById('HitbtcBidNXT').innerHTML = (data.hitbtcbid);
document.getElementById('HitbtcAskNXT').innerHTML = (data.hitbtcask);
});
$.getJSON('https://vip.bitcoin.co.id/api/nxt_btc/ticker', function(data) {
document.getElementById('priceLastNXT').innerHTML = (data.ticker.last);
document.getElementById('priceLashBuyNXT').innerHTML = (data.ticker.buy);
document.getElementById('priceLashSellNXT').innerHTML = (data.ticker.sell);
document.title = "NXT " + (data.ticker.last);
});
}
setInterval(price, 3000);
});
can I do this
function getMax(array){
return Math.max.apply(Math,array);
}
var NxtBid = document.getElementById("PoloniexBidNXT");
var NxtBid2 = document.getElementById("BittrexBidNXT");
var NxtBid3 = document.getElementById("HitbtcBidNXT");
var NxtBid4 = document.getElementById("priceLashBuyNXT");
var NxtBid5 = [NxtBid, NxtBid2, NxtBid3, NxtBid4];
var NxtBid6 = getMax(NxtBid5);
document.getElementById("NxtBidMax").innerHTML = NxtBid6;
I want to set low price and hi price from PoloniexLastNXT, BittrexLastNXT,HitbtcLastNXT, priceLastNXT.someone can help me
For Poloneix you can use assuming you have elements for "PoloniexLowNXT" and "PoloniexHighNXT",
$.getJSON('https://poloniex.com/public?command=returnTicker', function(data){
document.getElementById('PoloniexLastNXT').innerHTML = (data.BTC_NXT.last);
document.getElementById('PoloniexBidNXT').innerHTML = (data.BTC_NXT.highestBid);
document.getElementById('PoloniexAskNXT').innerHTML = (data.BTC_NXT.lowestAsk);
document.getElementById('PoloniexLowNXT').innerHTML = (data.BTC_NXT.low24hr);
document.getElementById('PoloniexHighNXT').innerHTML = (data.BTC_NXT.high24hr);
});
You could try Promise.all and do a forEach on the results. Instead of repeating the implementation code you could create an array of settings and loop over it to get the result and process them:
const settings = [
[
"https://poloniex.com/public?command=returnTicker",//url
["#PoloniexLastNXT","#PoloniexBidNXT","#PoloniexAskNXT"],//elements to set
[//how to get value
data=>data.BTC_NXT.last,
data=>data.BTC_NXT.highestBid,
data=>data.BTC_NXT.lowestAsk
]
]
//others
];
Promise.all(
settings.map(
([url],index)=>
$.getJSON(setting(url))
.then(
data=>[data,settings[index]]
)
)
).then(
results=>{
var lowestLast=Infinity,highestLast=-Infinity;
results.forEach(
([data,[url,querySelectors,getters]])=>{
querySelectors.forEach(
(querySelector,index)=>
document.querySelector(querySelector).innerHTML=getters[index](data)
)
const last = getters[0](data);
if(last<lowestLast){
lowestLast=last;
}
if(last>highestLast){
highestLast=last;
}
}
)
return [lowestLast,highestLast];
}
).then(
([lowest,highest])=>{
console.log("lowest:",lowest,"highest:",highest);
}
).catch(
err=>console.warn("something went wrong:",err)
);
update
If you want to continue using your own repetitive implementation then you can get min and max in this way:
const numbers = [
new Number(trim(document.getElementById("PoloniexBidNXT").innerText)),
new Number(trim(document.getElementById("BittrexBidNXT").innerText)),
new Number(trim(document.getElementById("HitbtcBidNXT").innerText)),
new Number(trim(document.getElementById("priceLashBuyNXT".innerText)))
];
const lowest = Math.max.apply(null,numbers);
const highest = Math.min.apply(null,numbers);

Javascript array.push() do not add but replace it

I have some checkboxes styled with bootstrapSwitch.
I wrote a script that have to add value of checkbox to an array when bootstrapSwitch state is true.
This is my code :
$('input[name^=skill]').on('switchChange.bootstrapSwitch', function (event, state) {
//alert(state);
//var s = [];
var s = new Array();
if( state === true )
{
//var value = $(this).val();
s.push( $(this).val() );
console.log(s);//(value)
}
console.log(s);//(value)
});
But surprisingly push method replace the value and my s array always have one index.
Would you please let me know why is that?
Thanks in Advance
var s = new Array();
Define this out of the handler function.
It's always 1 because you're recreating it everytime.
var s = new Array();// this line should be out side of function. so it will not be new object everytime
so try this
var s = new Array();// this line should be here. so it will not be new object everytime
$('input[name^=skill]').on('switchChange.bootstrapSwitch', function (event, state) {
//alert(state);
//var s = [];
var s = new Array();
if( state === true )
{
//var value = $(this).val();
s.push( $(this).val() );
console.log(s);//(value)
}
console.log(s);//(value)
});
var s = [];
$('input[name^=skill]').on('switchChange.bootstrapSwitch', function (event, state) {
//alert(state);
//var s = [];
if( state === true )
{
//var value = $(this).val();
s.push( $(this).val() );
console.log(s);//(value)
}
console.log(s);//(value)
});
Just declare the array outside. User [] instead on new Array() as it is faster.

create multidimensional array or object in jquery each loop

this is what I've got and been struggeling for hours. if I alert(i)in the each loop it gives me 1,2,3... but if I want to use as as key for a multidimensional array it is like a string "i"
$(document).ready(function(){
var positions=[];
$( ".box" ).each(function(i) {
//alert(i);
var elPositions = {};
elPositions.i = $(this).offset().top;
positions.push(elPositions);
//$elPosArray[i] = $(this).offset().top;
//$(this).html('outer height--> ' + $(this).outerHeight(true));
});
console.log(positions);
//console.log(el);
});
There are Questions and answers to this topic but none of them helped me to get this to work.
I would like to get an array or obj looking something like:
positions[0]['offset'] = '120';
positions[0]['height'] = '300';
positions[1]['offset'] = '420';
positions[1]['height'] = '180';
positions[2]['offset'] = '600';
positions[2]['height'] = '100';
positions[3]['offset'] = '700';
positions[3]['height'] = '300';
Here is a fiddle with the html http://jsfiddle.net/Z9WrG/
You're pretty much there!
In your loop, elPositions (here renamed data) is recreated new on each iteration, and then pushed into the array with a consecutive index. There's no need to specify i in the data object as i is assigned automatically when you push into the array.
See updated fiddle: http://jsfiddle.net/Z9WrG/2/
and code:
$(document).ready(function(){
var positions=[];
$( ".box" ).each(function() {
var $this = $(this);
var data = {};
data.offset = $this.offset().top;
data.height = $this.height();
positions.push(data);
// Now, positions[iteration_index] = { offset: x, height: y }
});
console.log(positions);
console.log(positions[0].height);
console.log(positions[0].offset);
});

Javascript array key value as a variable

I am trying to set up an array of keys that are strings instead of numbers. But, when I try to do so, the array ends up null.
Here is the function that works (where the keys are just a simple number "i":
function loadImages(arr, data, callBack){
var count = 0;
var img = new Array();
for(var i in arr ){
var src = "\""+arr[i]+"\"";
img[i] = new Image();
img[i].src = arr[i];
img[i].onload = function(){
count++;
if(count == arr.length){
callBack(data, img);
}
}
}
}
Here is the function I am attempting to use but the resulting array is null:
function loadImages(arr, data, callBack){
var count = 0;
var img = new Array();
for(var i in arr ){
var src = "\""+arr[i]+"\"";
img[src] = new Image();
img[src].src = arr[i];
img[src].onload = function(){
count++;
if(count == arr.length){
callBack(data, img);
}
}
}
}
I have tried defining "src" in the following ways too:
var src = arr[i];
var src = "'"+arr[i]+"'";
Does anyone know why it is resulting in null?
Javascript arrays are not good to be used for an enumerated array. That is what you are trying to do here. Use Object instead.
Then you can use a string as a key.
function loadImages( arr, data, callBack )
{
var nCount = 0 ;
var oImg = new Object() ;
for ( i = 0; i < arr.lenght; i++ )
{
var sSrc = "\"" +arr[ i ]+ "\"" ;
oImg[ sSrc ] = new Image() ;
oImg[ sSrc ].src = arr[ i ] ;
oImg[ sSrc ].onload = function()
{
count++;
if ( count == arr.length )
{
callBack( data, oImg ) ;
alert( oImg ) ;
}
}
}
}
JAVASCRIPT
function loadImages(arr, data, callBack){
var count = 0;
var img = new Array();
for(i=0; i<arr.lenght; i++ ){
var src = "\"" +arr[i]+ "\"";
img[src] = new Image();
img[src].src = arr[i];
img[src].onload = function(){
count++;
if(count == arr.length){
callBack(data, img);
alert(img);
}
}
}
}
Try this..

Javascript | Objects, Arrays and functions

may be you can help me. How can I create global object and function that return object values by id?
Example:
var chat = {
data : {
friends: {}
}
}
....
/*
JSON DATA RETURNED:
{"users": [{"friend_id":"62","name":"name","username":"admin","thumb":"images/avatar/thumb_7d41870512afee28d91.jpg","status":"HI4","isonline":""},{"friend_id":"66","name":"Another name","username":"regi","thumb":"images/avatar/thumb_d3fcc14e41c3a77aa712ae54.jpg","status":"Всем привет!","isonline":"avtbsl0a6dcelkq2bd578u1qt6"},{"friend_id":"2679","name":"My name","username":"Another","thumb":"images/avatar/thumb_41effb41eb1f969230.jpg","status":"","isonline":""}]}
*/
onSuccess: function(f){
chat.data.friends = {};
for(var i=0; i< f.users.length;i++){
chat.data.friends.push(f.users[i])
}
}
How can I create a new function (It will return values by friend_id)?
get_data_by_id: function (what, friend_id) {
/*obj.what = getfrom_globalobject(chat.data.friends???)*/
}
Example of use:
var friend_name = get_data_by_id(name, 62);
var friend_username = get_data_by_id(username, 62);
var friend_avatar = get_data_by_id(thumb, 62);
Try:
get_data_by_id: function (what, friend_id) {
return chat.data.friends[friend_id][what];
}
... but use it like:
var friend_name = get_data_by_id('name', 62);
...and set up the mapping with:
for(var i=0; i< f.users.length;i++){
chat.data.friends[f.users[i].friend_id] = f.users[i];
}
You cannot .push() to an object. Objects are key => value mappings, so you need to use char.data.friends[somekey] = f.users[i];
If you really just want a list with numeric keys, make x5fastchat.data.friends an array: x5fastchat.data.friends = [];
However, since you want to be able to access the elements by friend_id, do the following:
onSuccess: function(f){
x5fastchat.data.friends = {};
for(var i=0; i< f.users.length;i++){
chat.data.friends[f.users[i].friend_id] = f.users[i]
}
}
get_data_by_id: function (what, friend_id) {
obj[what] = chat.data.friends[friend_id][what];
}
Note the obj[what] instead of your original obj.what: When writing obj.what, what is handled like a string, so it's equal to obj['what'] - but since it's a function argument you want obj[what].
Take a look at the following code. You can simply copy paste it into an HTML file and open it. click "go" and you should see the result. let me know if I did not understand you correctly. :
<script>
myObj = { "field1" : { "key1a" : "value1a" }, "field2" : "value2" }
function go()
{
findField(myObj, ["field2"])
findField(myObj, ["field1","key1a"])
}
function findField( obj, fields)
{
var myVal = obj;
for ( var i in fields )
{
myVal = myVal[fields[i]]
}
alert("your value is [" + myVal + "]");
}
</script>
<button onclick="go()">Go</button>
I would recommend using the friend objects rather than getting them by id and name.
DATA = {"users": [{"friend_id":"62","name":"name","username":"admin","thumb":"images/avatar/thumb_7d41870512afee28d91.jpg","status":"HI4","isonline":""},{"friend_id":"66","name":"Another name","username":"regi","thumb":"images/avatar/thumb_d3fcc14e41c3a77aa712ae54.jpg","status":"Всем привет!","isonline":"avtbsl0a6dcelkq2bd578u1qt6"},{"friend_id":"2679","name":"My name","username":"Another","thumb":"images/avatar/thumb_41effb41eb1f969230.jpg","status":"","isonline":""}]}
// simple data store definition
Store = {items:{}};
NewStore = function(items){
var store = Object.create(Store);
store.items = items || {};
return store
};
Store.put = function(id, item){this.items[id] = item;};
Store.get = function(id){ return this.items[id]; };
Store.remove = function(id){ delete this.items[id]; };
Store.clear = function(){ this.items = {}; };
// example
var chat = {
data : {
friends : NewStore()
}
}
// after data loaded
chat.data.friends.clear();
for( var i = 0; i < DATA.users.length; i += 1 ){
var user = DATA.users[i];
chat.data.friends.put( user.friend_id, user );
}
getFriend = function(id){ return chat.data.friends.get( id ); }
var friend = getFriend(66);
console.log(friend.name);
console.log(friend.username);
console.log(friend.thumb);

Categories