我如何以这样的方式设计JSON的方式设计对象?

时间:2019-06-27 13:44:34

标签: javascript json angular data-structures

我的问题很简单。我想我只是想念一些东西。我基本上想迭代并将其添加到对象中,以便最终获得看起来像这样的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"
        }]
    }]
}

我尝试制作idmemfm数组,然后将它们推入对象,但出现错误 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"
``

任何指导将不胜感激。

2 个答案:

答案 0 :(得分:3)

您需要像这样声明数组:

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);

...

答案 1 :(得分:0)

您尚未将userData定义为数组。

userData=[]; idm=em=fm=[];
idm.push({name:"Jane Smith", email:"user1@example.com"},{name:"Jane Smith", email:"user1@example.com"});
em.push({name:"Jane Smith", email:"user1@example.com"},{name:"Jane Smith", email:"user1@example.com"});
fm.push({name:"Jane Smith", email:"user1@example.com"},{name:"Jane Smith", email:"user1@example.com"});
userData.push(idm);
userData.push(em);
userData.push(fm);