将对象文字插入到对象中的数组中

时间:2016-08-02 06:04:28

标签: javascript jquery

早上好! 我从表单值生成对象文字,然后将它们存储在数组中,如下所示



var persons  = {};// I want all the objects in the array to be inserted here so that I can stringify it and send via Ajax
var array = [];// where I store the object literals
var courses = {};
course['name'] = $('#course').val();
array.push(courses);
var students = {};
students['first'] = $('#first_name').val();
students['last'] = $('#last_name').val();
students['age'] = $('age').val();
array.push(courses);
// I tried this after the help I got this morning but it does not create multiple objects. When there are many successive values, the data sent is empty 
var persons = {
    courses: {
        name: $('#course').val(),
    },
    students: {
        name: $('#first_name').val(),
        last: $('#last_name').val(),
        age: $('#age').val(),
    },
};




请有人知道如何创建几个学生,并将他们与课程名称放在同一个对象中吗?

1 个答案:

答案 0 :(得分:0)

按如下方式更改您的代码

 courses = {
        name: $('#course').val(),
        students: []
 };

添加你做的学生:

courses.students.push({
        name: $('#first_name').val(),
        last: $('#last_name').val(),
        age: $('#age').val(),
    })