我在这里已经检查了关于stackoverflow的类似问题,阅读了javascript MDN,但没有找到可比较的示例,现在正在寻求有关如何从给定数组创建所需数组的建议。
所需的数组采用这种格式,而不是在每个数组元素处都是由一个键和一个值组成的对象,该值本身就是key:value对的对象。(如果您好奇为什么我要像这样对数组进行编码,则需要这种格式才能使用bind.js库)。
所需格式:
var userSummary = {
ryanc: {
"CreatedBy":"ryanc",
"New Contacts":7,
"New Invites (Challenge Groups)":8,
"New Invites (Coaching Opportunity)":9,
"New Follow Ups":12,
"New Challenger Check-Ins":11,
"Team Call Participation (National, upline team, or our team)":3,
"SCPoints":0,
"Volume":0
},
Pupperpie: {
"CreatedBy":"Pupperpie",
"New Contacts":5,
"New Invites (Challenge Groups)":4,
"New Invites (Coaching Opportunity)":3,
"New Follow Ups":3,
"New Challenger Check-Ins":5,
"Team Call Participation (National, upline team, or our team)":1,
"SCPoints":0,
"Volume":0
},
bowdenke: {
"CreatedBy":"bowdenke",
"New Contacts":14,
"New Invites (Challenge Groups)":3,
"New Invites (Coaching Opportunity)":3,
"New Follow Ups":1,
"New Challenger Check-Ins":0,
"Team Call Participation (National, upline team, or our team)":2,
"SCPoints":0,
"Volume":0
}
};
当前格式是这样的:
var userSummary = {
{
"Created By":"ryanc",
"New Contacts":7,
"New Invites (Challenge Groups)":8,
"New Invites (Coaching Opportunity)":9,
"New Follow Ups":12,
"New Challenger Check-Ins":11,
"Team Call Participation (National, upline team, or our team)":3,
"SCPoints":0,
"Volume":0
},
{
"Created By":"Pupperpie",
"New Contacts":5,
"New Invites (Challenge Groups)":4,
"New Invites (Coaching Opportunity)":3,
"New Follow Ups":3,
"New Challenger Check-Ins":5,
"Team Call Participation (National, upline team, or our team)":1,
"SCPoints":0,
"Volume":0
},
{
"Created By":"bowdenke",
"New Contacts":14,
"New Invites (Challenge Groups)":3,
"New Invites (Coaching Opportunity)":3,
"New Follow Ups":1,
"New Challenger Check-Ins":0,
"Team Call Participation (National, upline team, or our team)":2,
"SCPoints":0,
"Volume":0
}
};
目前,我已经尝试了此代码,该代码将插入文字“用户”而不是用户名,如下所示:
{"user":{"Created By":"ryanc","New Contacts":0,"New Invites (Challenge Groups)":0,"New Invites (Coaching Opportunity)":0,"New Follow Ups":0,"New Challenger Check-Ins":0,"Team Call Participation (National, upline team, or our team)":0,"SC Points":0,"Volume":0}}
数组uniqueUser包含一个用户名数组,userSummary应该包含新格式化的对象。
我也尝试了其他一些变体,但似乎语法不正确。
uniqueUsers.forEach(function(user) {
var obj = { user: {
'Created By': user,
'New Contacts': 0,
'New Invites (Challenge Groups)': 0,
'New Invites (Coaching Opportunity)': 0,
'New Follow Ups': 0,
'New Challenger Check-Ins': 0,
'Team Call Participation (National, upline team, or our team)': 0,
'SC Points': 0,
'Volume': 0
}}
userSummary.push(obj);
})
如果有其他想法,我将不胜感激,如果需要其他信息,请告诉我。
问题是这样的:
var obj = { user: {
^^
由于JS不需要对象键加引号,因此无法为此使用变量,因为您无法区分“ user-is-a-key”和“ user-is-a-variable”。
你必须要做
var obj = {};
obj[user] = {...}
相反,解析器将知道该user
变量是一个变量,而不是无引号的字符串。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句