const appData = {
articleCount: 0,
articles: [{
id: 1,
title: 'How to make money',
author: users[0].id,
content: 'Gather income streams',
createdat: '30/08/2018'
}],
users: [{
id: 1,
firstname: 'Michael',
lastname: 'Lee',
username: 'AuraDivitiae',
articles: [{id: 1}]
}]
}
我希望在我的appData对象和字段作者内部建立与同一对象内另一个字段的关联,这可能吗?
答案 0 :(得分:1)
您可以在对象初始化之后执行此操作:
appData.articles [0] .author = appData.users [0] .id;
const appData = {
articleCount: 0,
users: [{
id: 1,
firstname: 'Michael',
lastname: 'Lee',
username: 'AuraDivitiae',
articles: [{id: 1}]
}],
articles: [{
id: 1,
title: 'How to make money',
author: null,
content: 'Gather income streams',
createdat: '30/08/2018'
}]
}
appData.articles[0].author= appData.users[0].id;
console.log(appData.articles[0].author);
Getter
const appData = {
articleCount: 0,
users: [{
id: 1,
firstname: 'Michael',
lastname: 'Lee',
username: 'AuraDivitiae',
articles: [{id: 1}]
}],
articles: [{
id: 1,
title: 'How to make money',
content: 'Gather income streams',
createdat: '30/08/2018',
get author () {
return appData.users[0].id;
}
}]
}
//appData.articles[0].author= appData.users[0].id;
console.log(appData.articles[0].author);
答案 1 :(得分:1)
这是不可能的,但是您可以先创建用户变量,然后在对象文字中引用它,如下所示:
const users = [{
id: 1,
firstname: 'Michael',
lastname: 'Lee',
username: 'AuraDivitiae',
articles: [{id: 1}]
}]
const appData = {
articleCount: 0,
articles: [{
id: 1,
title: 'How to make money',
author: users[0].id,
content: 'Gather income streams',
createdat: '30/08/2018'
}],
users,
}
欢呼!
答案 2 :(得分:1)
您可以使用如下函数来实现它:
const appData = {
articleCount: 0,
articles: [{
id: 1,
title: 'How to make money',
author: ()=>appData.users[0].id,
content: 'Gather income streams',
createdat: '30/08/2018'
}],
users: [{
id: 1,
firstname: 'Michael',
lastname: 'Lee',
username: 'AuraDivitiae',
articles: [{id: 1}]
}]
}
console.log(appData.articles[0].author())