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 对象和字段作者内部与同一对象中的另一个字段相关联,这可能吗?
-
您可以在对象初始化后执行此操作:
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);
AFAIK 这是不可能的,但是您可以先创建 users 变量,然后在对象文字中引用它,如下所示:
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,
}
干杯!!
您可以使用函数来执行此操作,如下所示:
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())