javascript - 我如何以这样的方式设计一个对象,我可以像这样制定一个 JSON?

标签 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 数组,然后将它们推送到我的对象中,但出现错误 错误 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/

相关文章:

json - 如何通过 Swift 4 的 Decodable 协议(protocol)使用自定义 key ?

java - 输出html而不是json

javascript - 如何将toggleClass与相同类别的div一起使用但不影响其他div

javascript - 为什么将自定义 jQuery 插件名称添加到范围中

c# - 使用 json 序列化(反)序列化多个对象时出现 Null 问题

javascript - Angular 2 child 路由器 socket

javascript - 如何控制变量在Angular中不同组件中显示/隐藏

angular - 在无法识别的 ionic 5 错误元素中显示二维码 ngx-qrcode

JavaScript 文件加载顺序和依赖管理

javascript - jQuery 文本替换