我已经在 stackoverflow 上查看了类似的问题,阅读了 javascript MDN,但没有找到类似的示例,现在我正在寻求有关如何从给定数组创建所需数组的建议。
所需的数组采用这种格式,而不是每个数组元素都是一个由一个键和一个值组成的对象,该值本身就是键:值对的对象。 (如果您好奇为什么我要这样编码数组,我需要这种格式才能使用 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
是一个变量,而不是无引号字符串。
关于javascript - 使用 foreach 或带有 javascript 的 map 将复杂对象添加到数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39780418/