Popular an array of objects with a string

0

I have a string with the following content:

"Carlos Alberto   xxxxxxx    11/02/2016    $103.10
 Juliano Fontes   xxxxxxx    12/02/2016    $102.10
 Carlos ALberto   xxxxxxx    13/02/2016    $500.00"

I have my array with fields referring to this data, with the fields name, rg, date, and value. How to read this string and play row by row in array fields?

    
asked by anonymous 25.04.2016 / 12:16

2 answers

2

Here is one more suggestion. Handling data in this way is always risky because it can infiltrate errors. But here it is:

var texto = document.body.innerHTML.split('\n').filter(Boolean); // só para o exemplo do jsFiddle ir buscar texto
var linhas = texto.map(function(linha) {
    if (linha.match(/^\s+$/)) return; // linhas vazias
    linha = linha.split(/^\s+|\s+$/).join(''); // limpa linhas que começam ou acabam com espaços
    return linha.split(/[\s]{2,}/);
}).filter(Boolean);

var campos = ['nome', 'rg', 'data', 'value'];
var lista = {};

campos.forEach(function(campo, i) {
    lista[campo] = []; // criar a array para cada campo
    linhas.forEach(function(linha) {
        lista[campo].push(linha[i]); // adicionar valor à array
    });
});
console.log(lista);

Result:

{
    "nome": ["Carlos Alberto", "Juliano Fontes", "Carlos ALberto"],
    "rg": ["xxxxxxx", "xxxxxxx", "xxxxxxx"],
    "data": ["11/02/2016", "12/02/2016", "13/02/2016"],
    "value": ["$103.10", "$102.10", "$500.00"]
}

jsFiddle: link

If you have this text in a variable, just replace it:

var texto = document.body.innerHTML.split('\n').filter(Boolean);

by:

var texto = tuaVariavel.split('\n').filter(Boolean);
    
25.04.2016 / 14:12
1

WarLock, I see that it is working with a text file, where the separation of the columns is done by the size of the string.

In this case you will need to break the file in lines, using .split('\n') , then you will be able to use a substring to extract the fields.

Note that this type of file usually has a fixed size for each line, for example 60, in this case you should check if the line is not empty and has size 60

var nonFloat = /[^\d.\,]/gi;
var arquivo = document.getElementById("arquivo").content.textContent;

var parseDate = function (str) {
  var data = str.split("/");
  return new Date(parseInt(data[2]), parseInt(data[1]), parseInt(data[0]))
}

var registros = arquivo.split("\n").reduce(function (registros, line) {
  var start = 0; 
  var end = 0;
  
  if (line && line.length == 50) {
    var registro = {};
    start = end; end += 18; registro.nome = line.substring(start, end);
    start = end; end += 11; registro.rg = line.substring(start, end);
    start = end; end += 14; registro.data = line.substring(start, end);
    start = end; end += 07; registro.valor = line.substring(start, end);    
    
    registro.nome = registro.nome.trim();
    registro.rg = registro.rg.trim();
    registro.data = parseDate(registro.data);
    registro.valor = parseFloat(registro.valor.replace(nonFloat, ""));
    
    registros.push(registro);
  }
  return registros;
}, []);

console.log(registros);
<template id="arquivo">
 Carlos Alberto   xxxxxxx    11/02/2016    $103.10
 Juliano Fontes   xxxxxxx    12/02/2016    $102.10
 Carlos ALberto   xxxxxxx    13/02/2016    $500.00
</template>
    
25.04.2016 / 14:04