Search code examples
javascriptarraysobjectreference

Data structure in JS | Create reference to an object


In my app, I have quizzes with questions. I'm writing a class whose goal is to load and concat quizzes. I have two arrays in my class.

The first array contains the quizz meta data :

metadata = [
  {
    name:'countries', 
    language:'French'
  },
  {
    name:'music', 
    language:'English'
  }
]

I also have an array containing all the questions concatenated:

questions = [
  {
    question:'What is the capital of France?', 
    metaIndex: 0
  },
  {
    question:'What is the capital of Poland?', 
    metaIndex: 0
  },
  ...
  {
    question:'Who is the singer of the Rolling Stones?', 
    metaIndex: 1
  }
]

As you can see, the questions contain a reference to the meta data index. It's like a foreign key in relational database. My problem is that if I remove the quiz 0, it will shift all the indexes, and I'll have to iterate through the questions to update the indexes.

In JS, is there a way to reference directly the object instead of the index?

Any general suggestion is welcome ;-)


Solution

  • It's like a foreign key in relational database.

    Almost. Note that in a relational database, the order of returned records is not guaranteed unless explicitly defined. It can change on any given SELECT. (A subject which is often in question on Stack Overflow, but that's another conversation entirely.) But in this case the second data structure is referencing the positional index of elements in the first.

    If the index changes, either by changing the data or even simply sorting the data, that reference breaks.

    The analogy of a relational database is a reasonable one though, all you have to do is update the implementation to match that analogy. A foreign key references a primary key. Simply add a primary key of some kind. For example:

    metadata = [
      {
        id: 1,
        name:'countries', 
        language:'French'
      },
      {
        id: 2,
        name:'music', 
        language:'English'
      }
    ]
    

    Then the second data structure can reference that:

    questions = [
      {
        question:'What is the capital of France?', 
        metaID: 1
      },
      {
        question:'What is the capital of Poland?', 
        metaID: 1
      },
      {
        question:'Who is the singer of the Rolling Stones?', 
        metaID: 2
      }
    ]
    

    That way the index/order/etc. of the former structure can change, but as long as the objects therein still have their id values then the latter is still referencing them.

    In fact, if name is going to be unique in the former structure then that can be the identifier used. (Though in the data shown I'm not assuming it would be, for example if there's a countries entry in French and another one in English then that value wouldn't be unique.)