简体   繁体   English

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

[英]insert object literals pushed into array in an object

Good morning! 早上好! I generate object literals from form values and I store them in an array as follows 我从表单值生成对象文字并将其存储在数组中,如下所示

 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(), }, }; 

Please does anybody know how I can create several students and have them in the same object with the course name? 请问有人知道我如何创建几个学生并将他们与课程名称放在同一对象中吗?

Alter your code as follows 如下更改代码

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

to add a student you do: 添加学生,您可以:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM