Mklei
Mklei

Reputation: 75

How to form field associations within an object?

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

Answers (3)

NullPointer
NullPointer

Reputation: 7368

  1. 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);

  1. Use of 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

Emeeus
Emeeus

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

Ewomazino Ukah
Ewomazino Ukah

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

Related Questions