我的问题很简单。我想我只是错过了一些东西。我基本上想迭代并向对象添加内容,以便我最终可以获得如下所示的 JSON:
{
"user1": [{
"idm": [{
"name": "Jane Smith",
"email": "user1@example.com"
}],
"em": [{
"name": "Jane Smith",
"email": "user1@example.com"
}],
"fm": [{
"name": "Jane Smith",
"email": "user1@example.com"
}]
}],
"user2": [{
"idm": [{
"name": "John Smith",
"email": "user2@example.com"
}],
"em": [{
"name": "John Smith",
"email": "user2@example.com"
}],
"fm": [{
"name": "John Smith",
"email": "user2@example.com"
}]
}]
}
我尝试创建 idm
、em
和 fm
数组,然后将它们推送到我的对象中,但出现错误
错误 TypeError:无法获取未定义或 null 引用的属性“push”
。
我确定我缺少某些东西。
userData = {};
user = 'user1'
this.idm['name'] = name;
this.idm['email'] = email;
this.userData[user].push(this.idm);
this.em['name'] = name;
this.em['email'] = email;
this.userData[user].push(this.em);
this.fm['name'] = name;
this.fm['email'] = email;
this.userData[user].push(this.fm);
更新后:
this.userData = {};
array = ['user1', 'user2']
var i
for(i=0:i<array.length; ++i){
this.userData[array[i]] = []
this.idm['name'] = name;
this.idm['email'] = email;
this.userData[user].push(this.idm);
this.em['name'] = name;
this.em['email'] = email;
this.userData[user].push(this.em);
this.fm['name'] = name;
this.fm['email'] = email;
this.userData[user].push(this.fm);
}
我在控制台中的输出类似于:
[object Object]
-user1
--0
---name "Jane Smith"
---emial "user1@example.com"
--1
---name "Jane Smith"
---emial "user1@example.com"
--2
---name "Jane Smith"
---emial "user1@example.com"
-user1
--0
---name "John Smith"
---emial "user2@example.com"
--1
---name John Smith"
---emial "user2@example.com"
--2
---name John Smith"
---emial "user2@example.com"
``
如有任何指导,我们将不胜感激。
最佳答案
您需要像这样声明数组:
user = 'user1'
this.userData = { [user]: [] }; // or this.userData = {}; this.userData[user] = []
this.idm['name'] = name;
this.idm['email'] = email;
this.userData[user].push(this.idm);
...
关于javascript - 我如何以这样的方式设计一个对象,我可以像这样制定一个 JSON?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56792430/