How to create Associative Array in javascript, json, how to manipulate?

Asked

Viewed 443 times

2

It’s the first time I’ve dealt with this situation, so I don’t know exactly how to get around it. The fact is, I have a form with several inputs, divided by sections: Imagem do formulário seccionado por tabs

In Experience Tab, I fill some inputs with the data and when I click on add I create blocks with the data filled in as follows:

$('#'+destino).append(
    "<div class='blococurso box-experiencia'>"
    +"<label>Empresa:</label> <span class='content' data-content="+experiencia.empresa+">"+experiencia.empresa+"</span><br>"
    +"<label>Cargo:</label> <span class='content' data-content="+experiencia.cargo+">"+experiencia.cargo+"</span><br>"
    +"<label>Admissão:</label> <span class='content' data-content="+experiencia.admissao+">"+addDemissao.admissao.toString().replace(/,/g, '/')+"</span><br>"
    +"<label>Demissão:</label> <span class='content' data-content="+experiencia.demissao+">"+addDemissao.demissao.toString().replace(/,/g, '/')+"</span><br>"
    +"<label>Atividades:</label> <span class='content' data-content="+experiencia.atividades+">"+experiencia.atividades+"</span><br>"
    +"<i class='fa fa-close btn-fechar fechar-experiencia' data-destino='' data-funcao='remover'></i></div>"
  );

By clicking the save data button, I take all the inputs and put in obj javascript, and the data like this from the experience that are in Divs, I get like this:

$("#painel-experiencia .box-experiencia .content").each(function(index){ experiencia.push( $(this).text() ); });

Right now I have an Array similar to that; .["dasd", "asdas", "01/01/2017", "01/01/2017", "dasdasd", "asdasd", "asdasd", "01/01/2017", "01/01/2017", "asdasdaasd", "asdasda", "asdasd", "01/01/2017", "01/01/2017", "dsadasdas"]

But what I need is more for it: .[{"empresa": "asdas", "admissao": "01/01/2017", "demissao": "01/01/2017", "atividades":"dasdasd"}, {"empresa": "asdas", "admissao": "01/01/2017", "demissao": "01/01/2017", "atividades":"dasdasd"}]

What I look for is an associative array and a way to add each experience block as an array, within a wrapper array. What I need is more for json, if that’s the only way, how to insert the data into a Json and then wrap it in another json?

If you know any other way to reach the same end it would be very helpful.

  • The part about filling in inputs works well?

  • @Sergio , sorry I didn’t understand, fill in the inputs "company, position etc" if yes, the fill is normal, in the image I attached the data that are on the right are data entered by the inputs.

  • You tested/understood my answer?

2 answers

2


I think this might help you.

In your code include information in span to use as a key (date-key) in the dictionary.

$('#'+destino).append(
    "<div class='blococurso box-experiencia'>"
    +"<label>Empresa:</label> <span class='content' data-chave='empresa' data-content="+experiencia.empresa+">"+experiencia.empresa+"</span><br>"
    +"<label>Cargo:</label> <span class='content' data-chave='cargo' data-content="+experiencia.cargo+">"+experiencia.cargo+"</span><br>"
    +"<label>Admissão:</label> <span class='content' data-chave='admissao' data-content="+experiencia.admissao+">"+addDemissao.admissao.toString().replace(/,/g, '/')+"</span><br>"
    +"<label>Demissão:</label> <span class='content' data-chave='demissao' data-content="+experiencia.demissao+">"+addDemissao.demissao.toString().replace(/,/g, '/')+"</span><br>"
    +"<label>Atividades:</label> <span class='content' data-chave='atividades' data-content="+experiencia.atividades+">"+experiencia.atividades+"</span><br>"
    +"<i class='fa fa-close btn-fechar fechar-experiencia' data-chave='empresa' data-destino='' data-funcao='remover'></i></div>"
);

Rewrite your saving function that way:

function salvar(){
    experiencias = Array();
    $(".box-experiencia").each(function(index, obj){
        experiencia = {}
        $(".content", obj).each(function(index1, obj1){
          experiencia[$(obj1).attr('data-chave')] =  $(obj1).text();
        });
        experiencias.push(experiencia);
    });
    console.log(experiencias);
}

The first selector, $(".box-experiment"). each, searches only the Divs and iterates each one. The second selector searches for each span within the current div and assembles a dictionary with the information. At the end, the dictionary is included in the array of experiences.

Take the example: https://jsfiddle.net/3h1oafqc/13/

  • perfect guy, just that. Another question, when you assign experience[$(obj1). attr('key date')] = $(obj1). text(); You are creating a dictionary that would be an associative array, where the index is defined by the 'key date' attribute and then adds the value by . text()?

  • 1

    Yes. Exactly. As an example, if you did it manually it would look something like this: experience = Array(); experience['company']='test';

  • Perfect, thank you very much, brother! @fsola

1

To show an object with the values of these inputs replaces

experiencia.push($(this).text());

for

experiencia.push({[this.dataset.content]: $(this).text()});

But this notation to assign keys to objects with [] in the creation is very recent and the support can be weak, so you could do so:

var dados = $("#painel-experiencia .box-experiencia .content").get().reduce(function(obj, el){
    obj[el.dataset.content] = $(el).text();
    return obj;
}, {});

Browser other questions tagged

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