jQuery giving me "undefined" echoing json - javascript

I'm trying to print out "message"
JSON:
[{"outcome":false,"message":"This is the message"}]
I've tried 3 things, here are the outcomes of them...
console.log(msg) => [{"outcome":false,"message":"Your account is pending beta activation"}] (this is fine)
var x = $.parseJSON(msg);
console.log(x) gives me an object
console.log(x.message) gives me undefined
What's the correct way to access msg.message, if not like that?

You have an Object in an Array. Use index 0.
x[0].message;
If you're anticipating more Objects in the Array, you can use $.each to iterate the Array.
$.each(x, function(i, obj) {
console.log(obj.message);
});

It looks like your getting a json object containing an array returned, did you try:
console.log(x[0].message);

Your json is an Array of Object's
Instead you should be using
x[0].message;

Related

React-Native doesn't extract strings from associative array in map

I cannot put strings from the associative array to another associative array. This is very weird phenomenon. This is the code and result
[Code]
p.phone_score_list.map(par => {
console.log(`par`, par);
console.log(typeof par.ipa);
phoneScoreList.push({
ipa: par.ipa,
// ipa: par.phone,
phone: par.phone,
pronuncedIpa: par.pronuncedIpa,
qualityScore: par.quality_score,
soundMostLike: par.sound_most_like,
});
});
console.log(`phoneScoreList`, phoneScoreList)
The result is below.
"ipa" and "pronuncedIpa" are "n" in the par parameter but after inputting the ipa into another associative array like the above code, it's gonna be undefined. Do you know the reason and how to handle it?
This is phone_score_list.
It's possible that you're assigning references to an object that has since been dropped from memory. I would try to create a new object like so
const newObject = { ...par };
phoneScoreList.push(newObject);

Javascript string/object/array confusion with JSON

I'm having a Laravel backend return some errors via Validator. These errors are passed through a HTTP response made by angular, and returned in JSON format.
The object is structured as seen below:
That name object has a value, which is the actual message that I'm after.
Currently, using loops etc., I can only get the name of the array (name) as a string...
I sometimes get multiple arrays within this error object, and I won't always know their names, so how may I retrieve that 0-index value in each of them, in a loop?
Thanks for any help.
Edit #1
Looping through it like this:
for(var err in res.data.errors){
console.log(Object.err[0][0]);
}
Gives me a Cannot get [0] index of undefined
How about this:
let errors = Object.values(response.data.errors);
// errors is now an array of arrays containing the validation errors
errors.forEach( (errorArray) => {
console.log(errorArray[0]);
} );
Another approach would be using Object.keys() instead of values. This is similar to what you already tried, where you get the name of the error property as a string, and then use it to access each error array:
let keys = Object.keys(response.data.errors);
keys.forEach( (errorKey) => {
console.log('error type', errorKey);
let errorArray = response.data.errors[errorKey];
console.log(errorArray[0]);
} );

How to get id from array of Object?

I have data in response so here rcsaAssessmentData.data.lobCheckListDTOs is array , riskAsesCklstSessionKey is property of array , How can i get this key using filter or any other option.Below console is printing all objects but i just want value for the riskAsesCklstSessionKey.
So far tried code...
array.js
var opChecklist = rcsaAssessmentData.data.lobCheckListDTOs.filter(function(obj){
return obj.riskAsesCklstSessionKey;
console.log("opcheclist...............",obj.riskAsesCklstSessionKey);
});
$scope.challengesDTO.addChlngToChklst= obj.riskAsesCklstSessionKey;
This is what I think you mean:
You have an array of objects, rcsaAssessmentData.data.lobCheckListDTOs. Each of the objects in the array has a property called riskAsesCklstSessionKey. You are trying to get an array of those keys. If so, try this:
var keys = rcsaAssessmentData.data.lobCheckListDTOs.map(function(a) {return a.riskAsesCklstSessionKey;});

Loop through JSON object returned from cookie

I know there are a bunch of questions out there regarding this, but I have tried several different proposed solutions and get the same results for each one.
I am storing checkbox values in an array in the format timeArr = [ event-name-one: 0: 1404915600, 1: 1404917400 ]. When the array gets updated with a new key/value pair a cookie is updated which stores the array as a JSON object.
I am storing the JSON object in the cookie using jQuery.cookie('day', JSON.stringify(timeArr), {expires: 7}); which stores the array in the following format (returned from console.log();):
{"event-name-one":{"0":1405346400,"1":1405347600},"event-name-two":{"0":1405357200,"1":1405358400}}
In this instance event-name-one and event-name-two are the ID's of the checkboxes. I need to loop through the returned cookie value (JSON object) and check the checkboxes whos ID's are found in the returned cookie.
I have tried a few different loops, i.e. for(var k in cookieValue){} and jQuery.each(jQuery.parseJSON(cookieValue), function(i, v) {}); with no luck.
The for(var k in cookieValue) loop returns each letter of the object separately and the jQuery.each() loop returns this error: Cannot use 'in' operator to search for '76' in ...
How can I convert this JSON string back to an array so I can loop through it and get the 'keys'
jQuery.cookie() must stringify arrays automatically into JSON objects because in order to get the correct results from the loop I had to use jQuery.parseJSON() on the response twice.
Example:
var cookieVal = jQuery.cookie('day_planner');
jQuery.each(jQuery.parseJSON(jQuery.parseJSON(cookieVal)), function(i, v) {
console.log(i, v);
});
This loop returns event-name-one Object {0: "1405346400", 1: "1405347600"}

Can't get JSON to output

First try at using JSON. I have an ajax/php function that returns a JSON object. Back on the js side, I can see the object and output it to a div. It looks fine. I can print it to the console, still looks good. But when I try to iterate over it and expose the individual values, I just get 'undefined' in my console. I can't figure out what I am missing. Sorry it if's something obvious, but I don't see it. Thanks!
var jsonObj = JSON.parse(xmlhttp.responseText);
console.log(jsonObj); //<--looks perfect
console.log(jsonObj.length);
document.getElementById("rightsidebox").innerHTML=response; //<--looks good
for (var group in jsonObj) {
//each of these generates 'undefined' WHY???
//I get 4 'undefined' outputs for each group, so I know that my loop is iterating correctly
console.log(group.id);
console.log(group.day);
console.log(group.time);
console.log(group.name);
}
EDIT: Here is an example of one of the JSON objects being returned by my ajax call. In this example, I only have a single object inside of the array. Of course, there will typically be multiple objects:
[{"id":"7","day":"Thursday","time":"7:00 a.m.","name":"Sub 10:00"}]
EDIT 2: Given this array, I have to ask what the point of JSON is. I can return this array without having PHP encode it in JSON format. So, if all that comes back is just a javascript array, then what have I accomplished? Why not skip the JSON encoding in PHP and then iterate over the array? Clearly there is a reason for this, so I'm obviously missing something. Is there a better way to do what I am trying to accomplish? Thanks!
Consider the following:
var myJson = '{"groupA": {"id": 123, "name": "foo"}}';
var myObj = JSON.parse(myJson);
for (var i in myObj) {
console.log(i);
console.log(i.id);
console.log(myObj[i].id);
}
The expected output here is:
myGroup
undefined
123
This is because you loop is just assigning the 'key' of your object to the value i. If you were to iterate an array, instead of an object, you'd get indices instead of strings.
In the example JSON you've given, you have an array with one object in it. If you intend to have multiple objects in your array, something like this would be better:
for (var group in jsonObj) {
var thisGroup = jsonObj[group];
thisGroup.id; // Etc etc..
}
If you have the correct jsonObj, and you say that you do, you can use formatting to output the object in an easy to read form. You don't have to loop through it.
console.log(JSON.stringify(jsonObj, null, 1));
Not sure why this works, when my original for (var group in jsonObj) loop doesn't, but whatever...
for (var i=0; i < jsonObj.length; i++) {
console.log(jsonObj[i].id);
console.log(jsonObj[i].day);
console.log(jsonObj[i].time);
console.log(jsonObj[i].name);
}

Categories

Resources