Create object with array of internal objects

5

I'd like to create a "cast" object (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:

  

  • post should contain: title, author, and text ;
  •   
  • text should contain an undefined amount of: line and undo ;
  •   
  • line should contain an undefined amount of: character and date ;
  • Is it possible to build this crazy? How would I use this object?

    The idea was to be able to then transfer the instantiated objects this way and forwards using JSON.

        
    asked by anonymous 23.05.2017 / 04:25

    2 answers

    2

    You can choose objects or classes, it depends a bit 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 do calculations, modify itself or have methods then class is better.

    For objects you can do a factory function 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 : link

        
    23.05.2017 / 08:31
    3

    I think it would be something like this, you can add new objects to the array's using the 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]);
        
    23.05.2017 / 04:49