jquery each not working propertly while looping through - javascript

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);
});
});

Related

Can an objects property, which is a function, be recursively called within itself?

I keep getting an error "Uncaught TypeError: this.setTestType is not a function" when trying to recursively call my setTestType function in my object.
Is recursion not allowed when defining a function as an object property and trying to call itself?
var resultGaAuto = [{
bestPracticeID: "344033"
}];
var resultAuto = [{
bestPracticeID: "111111"
}];
var AST = {
handleSave: function() {
var data = {};
var gaRecords = this.processResults(resultGaAuto);
var autoRecords = this.processResults(resultAuto);
//console.log(gaRecords);
//console.log(autoRecords)
var testTypeGaRecords = this.setTestType(gaRecords, 5);
var testTypeAutoRecords = this.setTestType(autoRecords, 4);
console.log(testTypeGaRecords);
data.records = Object.assign({}, testTypeGaRecords,
testTypeAutoRecords);
console.log(data);
},
setTestType: function(obj, num) {
Object.keys(obj).forEach(function(key) {
if (key === "testResult") {
return (obj[key] = num);
}
//*******ERROR*******
return this.setTestType(obj[key], num);
});
},
processResults: function(results) {
var records = {};
$.each(results, function(i, result) {
records[result.bestPracticeID] = records[result.bestPracticeID] || {
violation: {
violationID: result.bestPracticeID
},
instances: []
};
records[result.bestPracticeID].instances.push({
lineNumber: 1,
element: "testEl",
attribute: "testAttr",
xpath: "testPath",
testResult: 3
});
});
return records;
}
};
AST.handleSave();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
The bound context of your anonymous function should be AST
setTestType: function(obj, num) {
Object.keys(obj).forEach(function(key) {
if (key === "testResult") {
return (obj[key] = num);
}
//*******ERROR*******
return this.setTestType(obj[key], num);
}.bind(AST)); // see the bound context!
}
Can an objects property, which is a function, be recursively called within itself?
Yes. There is no technical limitation here. Just incorrect code.
Uncaught TypeError: this.setTestType is not a function
this is wrong.
Fix
setTestType: function(obj, num) {
Object.keys(obj).forEach(function(key) {
if (key === "testResult") {
return (obj[key] = num);
}
//*******FIXED*******
return AST.setTestType(obj[key], num);
});
},
More
Read up on this : https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/this

How to turn $.each object to an array

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

always convert into object

Can I do something in Javascript that will automaticaly transform this:
var x = 0;
into the following (but only in memory-- I don't want to change the "view source"):
var x = {Value: 0};
For exemple:
var x = { Value: 0 };
function a(x) //This function doesn't work if the parameter is not an object, and it would be better if I didn't have to write { Value: 0 }
{
x.Value++;
}
a(x);
alert(x.Value);
The question lacks context and details, but maybe do it like this:
function transform(x) {
return { Value : x };
}
and then
x = transform(x);
have a look at watch and Object.watch() for all browsers?, e.g.:
var a = function (x) {
x.value++;
};
var myVariables = {};
myVariables.watch("x", function (prop, oldval, newval) {
if (typeof newval !== 'object') {
return {"value": newval};
};
});
myVariables.x = 0;
a(myVariables.x);
alert(myVariables.x.value);

Get name of key in key/value pair in JSON using jQuery?

Say I have this JSON:
[
{
"ID": "1",
"title": "Title 1",
},
{
"ID": "2",
"title": "Title 2",
}
]
How would I return the set of key names that recur for each record? In this case, ID, title.
I tried:
$.getJSON('testing.json', function(data) {
var items = [];
$.each(data, function(key, val) {
items.push(key +', ');
});
$('<p/>', {
html: items.join('')
}).appendTo('#content');
});
without success.
This is a JSON "database", and every "record" has the same keys. I just want a script that will tell me what the keys are, not test whether or not they occur in every entry.
This will give you an array of all the string properties that match across an array of objects. Is that what you are looking for?
$.getJSON('testing.json', function(data) {
var propertiesThatExistInAll = getPropertiesThatExistInAll(data);
});
var getPropertiesThatExistInAll = function(arr) {
var properties = $.map(data[0], function (prop, value) {
return prop;
});
var propertiesThatExistInAll = [];
$.each(properties, function (index, property) {
var keyExistsInAll = true;
// skip the first one since we know it has all the properties
for (var i = 1, len = data.length; i < len; i++) {
if (!data[i].hasOwnProperty(property)) {
keyExistsInAll = false;
break;
}
}
if (keyExistsInAll) {
propertiesThatExistInAll.push(property);
}
});
return propertiesThatExistInAll;
};
Something like this, perhaps?
items = [];
for (key in jsonobj) {
if (!itemExists(items, key)) {
items[items.length] = key
}
}
function itemExists(items, value) {
for (i = 0; i < items.length; i++) {
if (items[i] == value) {
return true
}
}
return false;
}
Of course, that will return items that exist in any one of the objects, not that exist in all. It's not entirely clear from your question if this is the solution you want.
This can probably be made more efficient/concise, but the function below will do it.
var testJson = [ {'oi' : 1, 'arf': 2, 'foo' : 0}, {'oi': 5, 'arf': 7}];
function commonKeys(j)
{
var fillUp = [];
for(var i in j[0])
fillUp.push(i);
for(var i = 1; i < j.length; i++)
{
var cur = j[i]; var curArr = [];
for (var i in cur) {curArr.push(i)};
fillUp = fillUp.filter(function(x) {return (curArr.indexOf(x) != -1);});
}
return fillUp;
}
alert(commonKeys(testJson)); //oi,arf (not foo)

Javascript Dynamic Grouping

I am trying to create a table, with some grouping headers.
All is well when i have 1 group, but how do i create dynamic groups?
This is what i have so far (for 1 group):
var groupby = '';
arrdata.each(function(element){
if (groupby != element.groupby) {
groupby = element.groupby;
tbody.push(groupby)
}
tbody.push(element)
})
How do i make it create dynamic groups?
You could group them into an Object first:
Array.prototype.groupBy = function(keyName) {
var res = {};
this.forEach(function(x) {
var k = x[keyName];
var v = res[k];
if (!v) v = res[k] = [];
v.push(x);
});
return res;
};
Then for .. in through the object:
var employees = [{first: ..., last: ..., job: ...}, ...];
var byJob = employees.groupBy('job');
for (var job in byJob) {
document.write('<h3>Job: '+job+'</h3>');
byJob[job].forEach(function(e) {
document.write('<p>'+e.last+', '+e.first+'</p>');
});
}
More generic solution. You can use it directly. Deep copy of objects used.
Please note that this solution is of polynomial time
Array.prototype.groupBy=function(property){
"use strict";function deepCopy(p) {
var c = {};
for (var i in p) {
if (typeof p[i] === 'object') {
c[i] = (p[i].constructor === Array)?[]:{};
deepCopy(p[i],c[i]);
}
else {
c[i] = p[i];
}
}
return c;
}
var retarr=[];
var len=this.length;
for(var i=0;i<len;i++){
var groupedlen=retarr.length,found=false;
for(var j=0;j<groupedlen;j++){
if(this[i][property]===retarr[j].key){
retarr[j].values.push(deepCopy(this[i]));
found=true;
break;
}
}
if (found === false) {
retarr.push({
key: this[i][property],
values: []
});
retarr[retarr.length-1].values.push(deepCopy(this[i]));
}
}
return retarr;
};
test case:
var arr=[{num: 1,key:911},{num: 2,key:22},{num: 3,key:23},{num: 4,key:222},{num: 4,key:2222},{num: 2,key:2},{num: 1,key:29},{num: 3,key:26},{num: 4,key:24}];
var grouped=arr.groupBy('num');
console.log(grouped);
try with this structure:
arrdata = [
{
"groupby": {fields},
"data":[{fields},{fields},{fields}]
},
{
"groupby": {fields},
"data":[{fields},{fields},{fields}]
},
{
"groupby": {fields},
"data":[{fields},{fields},{fields}]
},
]
jQuery.each(arrdata, function(element){
tbody.push(element.groupby)
jQuery.each(element.data , function(elementData){
tbody.push(elementData);
})
})

Categories

Resources