gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 11:03:06 24 4
gpt4 key购买 nike

我的问题很简单。我想我只是错过了一些东西。我基本上想迭代并向对象添加内容,以便我最终可以获得如下所示的 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com