首页 > 解决方案 > 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?

标签: javascript

解决方案


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

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


推荐阅读