I have a variable with some data (key/value):
var errors = JSON.parse(xhr.responseText);
Here is the content:
{
"vehicle.Model":"Le champ Model est requis.",
"vehicle.Brand":"Le champ Brand est requis.",
"vehicle.Registration":"Le champ Registration est requis."
}
I would like to loop into it and display the key and the value for each.
How to proceed?
Thanks.
var key;
for (key in errors) {
if (errors.hasOwnProperty(key)) {
console.log(key + " : " + errors[key]);
}
}
for (var key in errors) {
var code = key;
var label = errors[key];
...
}
Note that there is no guarantee regarding the iteration order in today's ECMAScript.
I'd recommend you to read MDN's Working with objects.
for( key in errors ){console.log(key + " = " + errors.key);}
Related
How can I find in JQuery input by name, if I have dot array syntax from Laravel?
Input example:
<input type="text" name="Payments[0][1][Amount]">
<input type="text" name="Reservations[0][Date]">
Laravel validation response from ajax request:
errors: {
Payments.0.1.Amount: "Field is required",
Reservations.0.Date: "Field should be date"
}
Problem: How can I looping through errors array in javascript access input names, if I only have array dot names?
For example, transform Payments.0.1.Amount to Payments[0][1][Amount], or Reservations.0.Date to Reservations[0][Date]
for (const [key, value] of Object.entries(errors)) {
key = somehowParseDotInputToArray(key); // how? :)
$('#app input[name="' + key + '"]').append( '<p class="error">'+ value +'</p>' );
}
Have allready found solution, maybe someone also helps :)
function DotArrayToJs(str){
var splittedStr = str.split('.');
return splittedStr.length == 1 ? str : (splittedStr[0] + '[' + splittedStr.splice(1).join('][') + ']');
}
Simply split the name in an error object from . . Using var $nameArr = name.split('.');
Suppose name = Reservations.0.Date it will be like
let nameArr = ['Reservations','0','Date']
then make name as you want so
var newName = $nameArr[0] + '['+ $nameArr[1] +']' + '[' +$nameArr[2] + ']';
newName will look like Reservations[0][Date]
loop this process for all name variable and make new error object.
Juste in case someone has multi-level arrays
function getFieldnameFromLaravelDotName(laravelDotName) {
let parts = laravelDotName.split(".");
let fieldName = "";
let prefix = "";
let suffix = "";
parts.forEach((part, i) => {
if (fieldName != "") {
prefix = "[";
suffix = "]";
}
fieldName += prefix + part + suffix;
});
return fieldName;
}
console.log(getFieldnameFromLaravelDotName("noDotInThis"));
console.log(getFieldnameFromLaravelDotName("one.level"));
console.log(getFieldnameFromLaravelDotName("many.level.array.plop"));
Hi all i am calling a javascript function on WebView in android. I am sending a JSON data which will pass value to html.
My JSON data is in following format i have checked using online tools it is valid.
{"Results":{"Number of Tests":"2","Latency(avg)":"17","Failure":"0%","Latitude":"12° 55' 35.5872'' N","Longitude":"77° 36' 4.16916'' E","Latency(max)":"18","Latency(min)":"17"},"TestStaus":"Passed","Test":"Game Test"}
I am using following code to display parsed result in html using jquery.
var jsonObject = JSON.stringify(vk);
document.write(jsonObject);
$.each($.parseJSON(jsonObject), function(k, v)
{
document.write("<tr><td>" + k + "</td><td>" + v + "</td></tr>");
});
It is giving me output in following manner
Parameter Value
Results [object Object]
TestStatus Passed
Test Game Test
Please help how to read all results. Why it is reading object object.
Just use recursion. You need to be able to handle multidimensional objects. Also, I usually use jquery for DOM or AJAX only. For something like this, you might not need it.
Your Json
var vk = {"Results":{
"Number of Tests":"2",
"Latency(avg)":"17",
"Failure":"0%",
"Latitude":"12° 55' 35.5872'' N",
"Longitude":"77° 36' 4.16916'' E","Latency(max)":"18",
"Latency(min)":"17"
},
"TestStaus":"Passed",
"Test":"Game Test"};
Recursive function
function drawJSON(obj){
for(var key in obj){
if(typeof obj[key] === 'object'){
drawJSON(obj[key]);
continue;
}
document.write("<div><span>" + key + "</span><span>" + obj[key] + "</span> </div>");
}
}
drawJSON(vk);
DEMO
The Results is object so it is showing as [object object]. You can do this by:
function printEach(jsonObject) {
$.each(jsonObject, function(k, v)
{
if(typeof v === 'object') {
printEach(v);
} else {
console.log("<tr><td>" + k + "</td><td>" + v + "</td></tr>");
}
});
}
var vk = {"Results":{"Number of Tests":"2","Latency(avg)":"17","Failure":"0%","Latitude":"12° 55' 35.5872'' N","Longitude":"77° 36' 4.16916'' E","Latency(max)":"18","Latency(min)":"17"},"TestStaus":"Passed","Test":"Game Test"};
var jsonObject = JSON.stringify(vk);
printEach($.parseJSON(jsonObject));
You can see the fiddle http://jsfiddle.net/58grs/1/
My "stack" is totally overflow, so I need a help :)
I trying to get all values from FORM and save them to associative array. Here is a code:
var dat = [];
$('form[name=' + form.name + '] input[name], form[name=' + form.name + '] select[name], form[name=' + form.name + '] textarea[name]').each(function(i,el) {
dat[$(this).attr('name')] = $(this).val();
});
I am waiting for all values become in dat after this piece of code, but it looks like dat is internal variable of .each() lambda function, so it is unavailable after .each() is completed.
How to return resulting dat[] from the cycle ?
Try this
function() getFormData(){
var dat = {};
$('form[name=' + form.name + ']').find('input[name], select[name], textarea[name]').each(function(i,el) {
dat[$(this).attr('name')] = $(this).val();
});
return dat;
}
This function will return a json object containing all the form elements name/value pair specified in the selector.
Hey guys! First of all, I know this kind of stuff is quite shitty, but that's the way I visualize achieving my goal.
Here is the deal: I have a JSon object that contains an array, but unfortunately, I have to iterate through the list of one JSon object, and then iterate throught that array I mencioned before. The JSon object look as follows (it is in portuguese, but you guys can understand it):
{"produtos":[{"Key":"DERIVADOS DE FERRO","Value":217816909},{"Key":"MADEIRAS,
SUAS MANUFATURAS E MOBILIÁRIO MÉDICO
CIRÚRGICO","Value":117812290},{"Key":"CELULOSE,
PAPEL E SUAS
OBRAS","Value":100086937},{"Key":"CARNE
SUÍNA","Value":81738783},{"Key":"CARNE
BOVINA","Value":74894768},{"Key":"CARNE DE
AVES","Value":65292433},{"Key":"Outros","Value":444520811}],"ano":2005,"tipo":1}
Produtos is the array I mentioned, and I have two other values that are important: ano (year) and tipo (type). My code look as follows:
jQuery.getJSON("/webportos/Porto/GraficoComercio?id=" + iddoporto.className + "&ano=2005", null, function (items) {
jQuery.each(items, function (itemNo, item) {
jQuery.each(item.produtos, function (dicNo, dic) {
options.series.push({ name: dic.Key, data: dic.Value});
options.title.text = "Comércio - "+item.ano;
options.yAxis.title.text = "Exportação";
options.tooltip.formatter = function () {
return '<b><u>' + this.series.name + '</u></b><br/><b>' + this.x + '</b>: ' + this.y + ' ';
}
});
});
chart = new Highcharts.Chart(options);
});
This piece of code makes Chrome javascript console to display:
ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js:32 Uncaught TypeError: Cannot read property 'length' of undefined
Can you guys help me out?
Is this because you're trying to use .each() on a non array?
jQuery.each(items, function (itemNo, item) {
From my understanding, jQuery.each(object, callback, args) is only for use on arrays. The first thing it does is make a call to object.length. So unless you have
[{"produtos":[{"Key":"DERIVADOS DE FERRO","Value":217816909},{"Key":"MADEIRAS, SUAS
MANUFATURAS E MOBILIÁRIO MÉDICO CIRÚRGICO","Value":117812290},{"Key":"CELULOSE, PAPEL E SUAS
OBRAS","Value":100086937},{"Key":"CARNE SUÍNA","Value":81738783},{"Key":"CARNE
BOVINA","Value":74894768},{"Key":"CARNE DE AVES","Value":65292433},
{"Key":"Outros","Value":444520811}],"ano":2005,"tipo":1}]
you're gonna get that error.
Additionally, you may take Diodeus's suggestion into consideration. jQuery.each is quite a bit less performant than just using a for to loop through your data.
You don't need jQuery to iterate through JSON data. Use plain old Javascript.
See this question: Display JSON/YAML hierarchy as a tree in HTML?
function renderJSON(obj) {
var keys = []
var retValue = ""
for (var key in obj) {
if(typeof obj[key] == 'object') {
retValue += "<div class='tree'>" + key
retValue += renderJSON(obj[key])
retValue += "</div>"
}
else {
retValue += "<div class='tree'>" + key + " = " + obj[key] + "</div>"
}
keys.push(key)
}
return retValue
}
This is trivial I know but I'm so used to OOP languages. I'm trying to figure out how to write out each name/value in either one alert or many, just so I can verify the data
var dCookieNameValuePairs = {};
for (i = 0; i < cookieValues.length; i++)
{
var akeyValuePair = aCookieValues[i].split("=");
dCookieNameValuePairs[keyValuePair[0]] = keyValuePair[1];
}
// display each name value pair testing
for (i = 0; i < dCookieNameValuePairs.length; i++)
{
alert("Name: " + dCookieNameValuePairs[] + "Value: " +
}
I'm stuck at the second for loop...I am not sure how to iterate through the dictionary and then focus on each name/value to spit it back.
You want to use for..in for enumerating through a dictionary/map.
for ( var prop in dCookieNameValuePairs ) {
if ( dCookieNameValuePairs.hasOwnProperty( prop ) ) {
alert( dCookieNameValuePairs[prop] )
}
}
I may have typo'd. Only use .length when you are dealing with an array [] or a custom array-like object that you defined to have .length populated.
for (i in dCookieNameValuePairs) {
alert("Name: " + i + " Value: " + dCookieValuePairs[i]);
}
See the "JavaScript Does Not Support Associative Arrays" section of this page for more details.
If you don't need an associative array, you might put the keys and values into an array of objects instead. So your first loop would look something like this:
for (i = 0; i < cookieValues.length; i++) {
var akeyValuePair = cookieValues[i].split("=");
dCookieNameValuePairs.push({key: akeyValuePair[0], value: akeyValuePair[1]});
}