【发布时间】:2019-06-27 13:44:34
【问题描述】:
我的问题很简单。我想我只是错过了一些东西。我基本上想迭代并将东西添加到一个对象中,以便我最终可以得到一个看起来像这样的 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 数组,然后将它们推送到我的对象中,但出现错误
ERROR TypeError: Unable to get property 'push' of undefined or null reference。
我确信我缺少一些东西。
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"
``
任何指导将不胜感激。
【问题讨论】:
标签: javascript json angular data-structures