Popular an object array with a string

Asked

Viewed 647 times

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 the fields referring to this data, with the fields name, rg, date and value. How to read this string and play row by row on the array fields?

  • Hello, Have an array [] or JSON {}? Between data will always have 2 spaces " "?

  • You can give an example of the result you want to get?

  • Hello, it’s a list of objects I’m going to use to fill a table, so it would be a json. var lista = { nome[], rg[], data[],value[]}; I want to fill in as a simple list for popular in a table.

  • The spaces will always be 2.

  • Do you mean the spaces between fields of each line? Will they always be 2? (Because in your example are more than two spaces between fields)

  • @Sergio is right. Are there always 2 spaces and all the data? (even between lines)

Show 1 more comment

2 answers

2


Here’s another suggestion. Treating data 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);

Upshot:

{
    "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: https://jsfiddle.net/z7k427pu/


If you have that text in a variable just replace:

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

for:

var texto = tuaVariavel.split('\n').filter(Boolean);

1

Warlock, I see that you are working with a text file, where the separation of the columns is made by the size of the string.

in this case you will need to break the file into lines, using the .split('\n'), then you can 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>

  • JSON is not as requested. var lista = { name[], rg[], data[],value[]};

  • 1

    @Tiagogomes, really, but Sergio’s answer already covers this and other demands of the AP, I will leave this answer if the AP realizes that it really is a fixed-width text file.

Browser other questions tagged

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