[英]How to dynamically add to a JavaScript object?
I can't seem to figure out how to get the following results... 我似乎无法弄清楚如何获得以下结果...
var errors;
errors = { username: "username_error", email: "email_error" };
...when looping through data in this code: ...在此代码中遍历数据时:
var errors = {}
$.each(data,function(k,v)
{
errors[k] = v; // doesn't seem to work
});
It does produce an object yet in a different format. 它确实会产生一个对象,但格式不同。
EDIT: console log. 编辑:控制台日志。
Expected results: 预期成绩:
Object
email: "email_error"
username: "username_error"
__proto__: Object
edit:25
Object
__proto__: Object
Generated results: 产生的结果:
Object
email: Array[1]
0: "email_error"
length: 1
__proto__: Array[0]
username: Array[1]
0: "username_error"
length: 1
__proto__: Array[0]
__proto__: Object
By the results you posted with the log output, it seems the objects in data
are arrays. 根据您在日志输出中发布的结果,似乎
data
中的对象是数组。 Try replacing the assignment with this: 尝试用此替换任务:
errors[k] = v.length>0 ? v[0] : ""
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.