Reputation: 75
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}]
}]
}
I want inside my appData object and the field author to have an association to another field within the same object, is this possible?
Upvotes: 2
Views: 47
Reputation: 7368
You can do it after object initialization:
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);
Upvotes: 1
Reputation: 5250
You could do it using a function, like this:
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())
Upvotes: 1
Reputation: 2366
AFAIK this is not possible, however you can create the users variable first then reference it in your object literal like this:
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,
}
cheers!!
Upvotes: 1