Create object with internal object array

Asked

Viewed 1,028 times

5

I would like to create an object "mold" (maybe a class, maybe a function), with possibly other objects inside it, and arrays. The structure I imagine is like this:

postagem: {
    titulo: "",
    autor: "",
    texto: [
        {
            linha: [{
                caractere: '', // isso deveria ser um objeto
                data: string, // objeto date?
            }],
            desfazer: ?, // objetos caractere/data
        }
    ],
}

Explaining:

  • posting must contain: title, author and text;
  • text shall contain an indefinite amount of: line and undo;
  • line shall contain an indefinite amount of: date and character;

  • Is this crazy construction possible? How I would use that object?

    The idea was to be able to transfer the instantiated objects this way from here to there using JSON.

    • Can you explain that part? "text must contain an undefined amount of: line and undo;"

    • @Paulosérgioduff text would be an array of "line" objects and "undo" objects, in my current conception

    • I edited the answer, making "line" an object.

    • What are the variables you need to know to create the object and which are common?

    • @Sergio if I understood your question, there are no common variables - when instantiating, I imagined instantiating only with title and author - text with line/character/date would be added later, along the execution of the program

    2 answers

    3

    I believe it would look something like this, you can go adding new objects in the array’s through the method push();

    var caractere = {
      nome: 'Daniel'
    };
    var data = new Date();
    var linha = {
      caractere: [caractere],
      data: [data]
    }
    var desfazer = {
      caractere: [caractere],
      data: [data]
    }
    
    var postagem = {
      titulo: 'StackOverFlow',
      autor: 'Mathias',
      texto: [linha, desfazer]
    };
    
    //O mais próximo que consegui da maneira presente na pergunta:
    /*var postagem = {
      titulo: "",
      autor: "",
      texto: {
        linha: {
          caractere: [],
          data: []
        },
        desfazer: {
          caractere: [],
          data: []
        }
      }
    }*/
    
    console.log(postagem.titulo);
    console.log(postagem.autor);
    console.log(postagem.texto[0].caractere[0].nome);
    console.log(postagem.texto[0].data[0]);

    • Interesting! I’ll try this - actually "undo" would also be a "line" object, (has the same structure, only another name). And build the way I tried on the question, do you know if it’s possible? Oh, and thank you for the answer! :)

    • I arranged there @Danielgomes, I also left indicated as close as I could leave the idea of the question :)

    • I liked your edition! It was more or less what I wanted - last doubt: can turn this your commented code in a class or function, so that I can instantiate several of these objects, ex.: var a = new postagem("Stack", "Mathias");?

    • Ah, and linha and desfazer are arrays of arrays - I put in this fiddle to test, but I’m still cracking my head (I’m too dumb!)

    2


    You can choose objects or classes, it depends a little if you want something passive or active. That is, if you only want to group data, an object serves well; if you want each object to be able to do calculations, modify itself or have methods then class is better.

    For objects you can make a function "Factory" (generator/factory) like this:

    function objFactory(title, author) {
      return {
        titulo: title || '',
        autor: author || '',
        texto: [{
          linha: [{
            caractere: '',
            data: null,
          }],
          desfazer: null,
        }],
      }
    }
    
    var excerto = objFactory('Lusiadas', 'Camões');
    console.log(JSON.stringify(excerto));

    Using classes:

    class Excerto {
      constructor(title, author) {
        this.titulo = title || '';
        this.autor = author || '';
        this.texto = [{
          linha: [{
            caractere: '',
            data: null,
          }],
          desfazer: null,
        }];
      }
    }
    
    var excerto = new Excerto('Lusiadas', 'Camões');
    console.log(excerto.titulo);

    If you want to develop more you can do something like this:

    function objFactory(title, author) {
      return {
        titulo: title || '',
        autor: author || '',
        texto: [],
      }
    }
    
    var autor = document.querySelector('input[name="autor"]');
    var titulo = document.querySelector('input[name="titulo"]');
    var iniciar = document.querySelector('button');
    
    function verificarAutoria() {
      iniciar.disabled = !autor.value.trim() || !titulo.value.trim();
    }
    
    autor.addEventListener('input', verificarAutoria);
    titulo.addEventListener('input', verificarAutoria);
    iniciar.addEventListener('click', function() {
      var textarea = document.createElement('textarea');
      document.body.appendChild(textarea);
      var obj = objFactory(titulo.value, autor.value);
      var linha = [];
      obj.texto.push({
        linha: linha,
        desfazer: null,
      });
      textarea.addEventListener('keyup', function(e) {
        if (e.keyCode == 13) { // Enter, mudar a linha
          linha = [];
          obj.texto.push({
            linha: linha,
            desfazer: null,
          });
        } else {
          var caractere = String.fromCharCode(e.keyCode);
          linha.push({
            caractere: caractere,
            data: new Date(),
          });
        }
        console.log(JSON.stringify(obj))
      });
    });
    <input type="text" name="autor" />
    <input type="text" name="titulo">
    <button type="button" disabled>Iniciar</button>

    jsFiddle: https://jsfiddle.net/rpohrz8q/

    Browser other questions tagged

    You are not signed in. Login or sign up in order to post.