How to make such a structure?
What type of structure is this, and how to I make such using a lo开发者_如何学JAVAop?
var movies = [
{ Name: "The Red Violin", ReleaseYear: "1998" },
{ Name: "Eyes Wide Shut", ReleaseYear: "1999" },
{ Name: "The Inheritance", ReleaseYear: "1976" }
];
I am using each
for the loop
$.each(result, function(key, value){
movies??? = this.name;
movies??? = this.year;
});
It's an array of objects:
var movies = [];
$.each(result, function(key, value){
movies.push({Name: this.name, ReleaseYear: this.year});
});
You can see that the wrapping structure is an array:
$.isArray(movies); // true
And that each element is an object:
$.isPlainObject(movies[0]); // true
It's an array of JSON objects. To add a "movie", just do:
movies.push({Name: "Kung Fu Panda 2", ReleaseYear: "2011"});
var movies = [];
$.each(result, function(key, value){
movies.push( { Name: this.name, ReleaseYear: this.year });
});
Assuming there's some movies array object in you loop you can populate it with the name year objects like this:
movies.push({Name: "name", ReleaseYear: "2011"});
var movies = $.map(results, function(v) {
return { Name: v.name, ReleaseYear: v.year };
});
$.map
@davin covered the implementation, but though I'd cover the initial question.
The object you're looking to create is the object literal notation of javascript.
More commonly you'll see this same syntax used when transferring information between JS and other technologies (though it can be used in technologies other than JS since it is a standard). In these instances (when serialized) the information is considered to be in JSON (Javascript Object Notation) [wikipedia] [RFC 4627]
This is an array of objects. An array is like a list, so this would be a list of objects. Each object has two properties: Name and ReleaseYear. I'm not sure where your data is coming from, but try something like this:
var movies = new Array();
$.each(result, function(key, value){
movies.push({Name: this.name, ReleaseYear:this.year})
});
精彩评论