Hello i wanted to ask how to access array in javascript from JSON object like this:
Object {results: "success", message: "Your message have been sent successfully", error_id_array: Array[1]}
error_id_array: Array[1]
0: "2"
length: 1
__proto__: Array[0]
message: "Your message have been sent successfully"
results: "success"
__proto__: Object
This question is related to this How to work with array returned from PHP script using AJAX? question. Thank you
asked Nov 21, 2013 at 13:01
user2945241
3605 silver badges19 bronze badges
-
1That is not a valid JSON object. And I say "JSON object", there is no such thing as JSON is the notation to describe an object, but not an object in and of itself.Moo-Juice– Moo-Juice2013年11月21日 13:04:58 +00:00Commented Nov 21, 2013 at 13:04
-
This come from ajax call?, and you want access to de arrays into the object?Gonzalo Bahamondez– Gonzalo Bahamondez2013年11月21日 13:13:56 +00:00Commented Nov 21, 2013 at 13:13
1 Answer 1
As Moo-Juice said, that is not a valid object. Here is an example of a valid object and how you would access its properties:
var myObj = {
myString : 'Hello world!',
myArray : ['red', 'yellow', 'blue'],
alertString : function() {
var message = this.myString;
for (var i = 0; i < this.myArray.length; i++) {
message += ' ' + this.myArray[i];
}
alert(message);
}
};
myObj.alertString();
// triggers a modal that says 'Hello world! red yellow blue'
answered Nov 21, 2013 at 13:17
Neil Girardi
5,0113 gold badges37 silver badges49 bronze badges
Sign up to request clarification or add additional context in comments.
3 Comments
Neil Girardi
@Moo-Juice JSON = JavaScript Object Notation. Therefore it is rather silly to say that a JavaScript object is not JSON. If you are talking about using JSON to transfer data between JS and your backend implementation language (ie Java, PHP, etc.) then yes, you would not send a method. You would send data consisting of strings, booleans, integers, floats, etc. Either way the notation is the same. {key1 : value1, key2 : value2}
Moo-Juice
I see what you were getting at now, whilst the OPs object is not a valid JSON object - your answer shows how to work with a javascript object.
Neil Girardi
@ Moo-Juice Exactly! Although my answer was technically off-topic since the OP's original question related to moving data between PHP and JS. Thank you for pointing out the discrepancy. Some times I get excited about sharing information and I go a bit off topic. :-) Cheers -- n
lang-js