How to turn $.each object to an array - javascript

I have a json, I $.each videolist and try to get the second. Then, I wish to turn the second into array[], easy for me to do next function that I want. Just not sure how to turn it into array.
var videoinfo = [{
"startdatetime": "2014-12-21 00:23:14",
"totalsecondrun": "2019402310",
"videolist": [{
"videoid": "uoSDF234",
"second": "10"
}, {
"videoid": "0apq3ss",
"second": "14"
}]
}];
var calduration = function() {
var list = videoinfo[0].videolist;
$.each(list, function(index, value) {
alert($.makeArray(value.second));
});
};
calduration();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
I expected the output should be [10,14].

If you insist on using a $.each() loop, as you title implies, here is one approach:
var calduration = function () {
var duration = [];
$.each(videoinfo[0].videolist, function (index, value) {
duration.push(parseInt(value.second, 10));
});
return duration;
};
Example Here
I'd suggest using $.map(), though:
var calduration = function () {
return $.map(videoinfo[0].videolist, function (value, index) {
return parseInt(value.second, 10);
});
};
..or .map():
return videoinfo[0].videolist.map(function (value, index) {
return parseInt(value.second, 10);
});
Example Here
And if you want to use plain JS:
var calduration = function () {
return Array.prototype.map.call(videoinfo[0].videolist, function(value){
return parseInt(value.second, 10);
});
};
Example Here

Related

Pass vars to other method javascript

I want to pass var "firstWord" with saved value in it from one method to another.
var obj = {
getWords: function () {
var words = [];
$('input').each(function () {
words.push($(this).val());
});
var firstWord = words[0],
secondWord = words[1],
thirdWord = words[2];
},
pushWords: function () {
Array.prototype.insert = function (index, item) {
this.splice(index, 0, item);
};
var fruits = ["Banana", "Orange", "Apple", "Mango"],
randomPosition = (Math.floor(Math.random() * (5 - 2 + 1)) + 1);
fruits.insert(randomPosition, firstWord);
$('body').append(fruits);
}
};
Probably my code is wrong a bit, but is there any possibility to do that in this case?
If you declare a varible with the var keyword, it's a only available in the function. Leave it out and you'll have a global variable, which you can access from other functions as well. (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var)
One way it to pass one function's value to the other, like:
function one(){
var var1 = "hello";
two(var1);
}
function two(x){
alert(x);
}
This should print "hello" for you.
The other way is to declare your firstWord as a global variable.
Try to return the array like below,
getWords: function () {
var words = [];
$('input').each(function () {
words.push($(this).val());
});
return words;
},
and in push words
pushWords: function () {
var arr = this.getWords();
................
................
................
fruits.insert(randomPosition, arr[0]);
}
$('body').append(fruits);
since var firstword,secondword and thirdword are only accessible inside the getwords function you must try to return it. And don't forget to validate the
return value before you use it. Hope it helps..
See example here https://jsfiddle.net/xz0ofkjx/
So make it a property of the object.
var obj = {
_words : [],
setWords : function () {
this._words = ["hello","world"];
},
pushWords : function () {
this._words.push("foo");
},
readWords : function () {
console.log(this._words);
}
}
obj.readWords();
obj.setWords();
obj.readWords();
obj.pushWords();
obj.readWords();

jquery each not working propertly while looping through

I am not able to figure out, why this code (only js) is not running - http://jsfiddle.net/fLEAw/
populateList();
populateList: function () {
var accData = [{ A: "A1" }, { B: "B1"}];
$.each(accData, function (index) {
alert(accData[index].Value)
});
}
You javascript/jquery code has multiple issues. have a look at this
var populateList = function () {
var accData = [{ A: "A1" }, { B: "B1"}];
$.each(accData, function (index) {
for(var value in accData[index]){
alert(accData[index][value])
}
});
}
populateList();
I would rather suggest you to rectify the issues your self and ask in comment.
http://jsfiddle.net/fLEAw/3/
You can use $.each to loop arrays and objects:
$.each(accData, function(i, obj) {
$.each(obj, function(k, value) {
alert(value);
});
});
I doubt you'll end up using alert, you probably want the values to do something with them, so you can put them in an array. Here's an alternative re-usable approach in plain JavaScript:
var values = function(obj) {
var result = [];
for (var i in obj) {
result.push(obj[i]);
}
return result;
};
var flatten = function(xs) {
return Array.prototype.concat.apply([], xs);
};
var result = flatten(accData.map(values));
console.log(result); //=> ["A1", "B1"]
Change
populateList: function () {
to
function populateList() {
Write:
populateList();
function populateList() {
var accData = [{
A: "A1"
}, {
B: "B1"
}];
var len = accData.length;
for (var i = 0; i < len; i++) {
$.each(accData[i], function (key, value){
//key will return key like A,B and value will return values assigned
alert(value)
});
}
}
Updated fiddle here.
Since your array element is object, try this solution:
var populateList = function () {
var accData = [{ A: "A1" }, { B: "B1"}];
$.each(accData, function (index) {
for(var ele in accData[index]){
alert(accData[index][ele]);
}
});
};
populateList();
Demo
try something like this
var accData = [{ A: "A1" }, { B: "B1"}];
$.each(accData, function (index,obj) {
$.each(obj, function(key, value) {
alert(key + '' + value);
});
});

Why can't I access JS object properties?

I have the following function:
function getAggregateData(){
var sums = new Object();
$.getJSON("example.json.php", function(data) {
//for each month
c = 0;
$.each(data, function(key, val, index) {
//for each store
$.each(val, function(key2, val2, index2) {
if(c == 0){
sums[key2] = val2;
}
else{
sums[key2] += val2;
}
});
c++
});
})
return sums;
}
Which I then call as such:
var totals = getAggregateData();
But when I console log I am totally stumped:
console.log(totals)
reveals an object like this:
store1 500
store2 900
store3 750
and so on and so forth...
but when I do console.log(totals['store1') I get undefinded.
I have also tried console.log(totals.store1)
and console.log(totals[0].store1)
I am having some type of issue of scope, or I am not creating the object I think I am.
It looks like the function would be returning an empty object since it's not waiting for the AJAX call to finish.
If you tried doing console.log(totals.store1) on the last line inside your $.getJSON callback you'll probably get a result.
You'll need to put any code that requires data from "example.json.php" inside a callback that only gets run after the AJAX call has returned.
E.g.
function getAggregateData(){
var sums = new Object();
$.getJSON("example.json.php", function(data) {
//for each month
c = 0;
$.each(data, function(key, val, index) {
//for each store
$.each(val, function(key2, val2, index2) {
if(c == 0){
sums[key2] = val2;
}
else{
sums[key2] += val2;
}
});
c++
});
processAggregateData(sums);
})
}
function processAggregateData(totals) {
console.log(totals.store1);
}
getAggregateData();
given:
{
"1": {
"store1": 2450,
"store2": 1060,
"store3": 310
},
"2": {
"store1": 2460,
"store2": 1760,
"store3": 810
}
};
This should work if you intend to add the results for each store.
/**
* This functions need to be called when we have the data
*/
function processSums(obj){
console.log(obj);
}
function getAggregateData(){
var sums = {};
$.getJSON("example.json.php", function(data) {
$.each(data, function() {
$.each(this, function(key, val, index){
sums[key] = sums[key] || 0;
sums[key] += val;
});
});
// 4910
processSums(sums);
});
return sums;
}
getAggregateData();

javascript keys and objects

I have a javascript code below:
function init() {
var data_pie = [];
var data_key = [];
data_pie.push(10,12,30,40,80,25);
data_key.push("x1","x2","x3","x4","x5","x6");
g.update(data_pie, data_key);
}
update: function(data, key) {
var i=-1;
var streakerDataAdded = d3.range(data.length).map(function() {
i++;
return {
name: key[i],
totalPlayers: data[i]
}
});
}
How can I optimize my code to use this object:
var data='{"data":[{"x1":"10","x2":"12","x3":"30","x4":"40","x5":"80","x6":"25"}]}';
Instead data_pie and data_key arrays?
Without being able to test this (not having any access to the rest of your code), you might try something like:
function init() {
var data='{"data":[{"x1":"10","x2":"12","x3":"30","x4":"40","x5":"80","x6":"25"}]}';
for(key in data.data[0]){
g.update(data.data[0][key], key, data.data[0].length);
}
}
update: function(data, key, length) {
var streakerDataAdded = d3.range(length).map(function() {
return {
name: key,
totalPlayers: data
}
});
}
It is very unclear as to why you would use such a data structure but anyway, here we go:
var jsonData = '{"data":[{"x1":"10","x2":"12","x3":"30","x4":"40","x5":"80","x6":"25"}]}';
// var cleanerJsonData = '{"x1":"10","x2":"12","x3":"30","x4":"40","x5":"80","x6":"25"}';
function update(json){
var data = JSON.parse(json).data[0]; // why use an array here?
// var data = JSON.parse(json) - using cleanerJsonData.
var streakerDataAdded = d3.map(data).entries().map(function(d){
return {name: d.key, totalPlayers: d.value} })
}
}

Return a value with jQuery each() function

i'm new to javascript, and I would like to retrieve values from JSON and push it into an array so that I can parse again this array in another function, But I don't know how to return the array after pushing element inside it.
In the following script I can't display values in items
function gC(b,c,p) {
$.getJSON('getmonths', 'b='+b+'&c='+c+'&p='+p, processJSON);
}
function processJSON(data) {
var retval = [];
$.each(data, function(key, val) {
retval.push(val);
//alert(retval.pop());
});
return retval;
}
$(document).ready(function(){
var b = $("#b").val();
var c = $("#c").val();
var p = $("#p").val();
var items = [];
items = gC(b,c,p);
var i = 0;
$('td').each(function(index) {
$(this).attr('bgcolor', items[i]);
i++;
}
How could I access the array ?
thank !
You don't return from an AJAX call, you have it call a callback function when it's done.
function gC(b,c,p) {
var retval = [];
$.getJSON('getmonths', 'b='+b+'&c='+c+'&p='+p, processData);
}
function processData(data){
var retval = [];
$.each(data, function(key, val) {
retval.push(val);
//alert(retval.pop());
});
alert(retval);
}
processData would be called when the AJAX call is done. This can't return a value to another function, so all your logic has to be inside this callback function.
UPDATE: You can also pass in a callback function to gC to be called when it's done.
function gC(b,c,p,f) {
var retval = [];
$.getJSON('getmonths', 'b='+b+'&c='+c+'&p='+p, function(d){
if(typeof f == 'function'){
f(d);
}
});
}
Then you call gC like so:
gC(b,c,p,function(data){
var retval = [];
$.each(data, function(key, val) {
retval.push(val);
//alert(retval.pop());
});
alert(retval);
});
UPDATE2: I saw the code you added to the question. This needs to be done in the callback.
gC(b,c,p,function(data){
var items = [];
$.each(data, function(key, val) {
items.push(val);
});
$('td').each(function(index){ // You don't need a separate i variable
// you can just use the index from the loop
$(this).attr('bgcolor', items[index]);
}
})
Just have the code inside the callback:
function processJSON(data) {
var retval = [];
$.each(data, function(key, val) {
retval.push(val);
});
$('td').each(function(index) {
if (index < retval.length)
$(this).attr('bgcolor', retval[index]);
});
}

Categories

Resources