Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

196
Visualizações
How To Create Multiple Arrays From a Single Array?

I getting form data in my console like this:

{item[0][sku]: 'EC1000-WMK', item[0][qty]: '1', item[1][sku]: 'POP-11', item[1][qty]: '1', form_key: 'ZuQxqBMHmidjUxEt'}
form_key: "ZuQxqBMHmidjUxEt"
item[0][qty]: "1"
item[0][sku]: "EC1000-WMK"
item[1][qty]: "1"
item[1][sku]: "POP-11"

This is how the above data created:

        $.fn.getFormData = function(){
            var data = {};
            var dataArray = $(this).serializeArray();
            console.log(data);

            console.log(dataArray);
            for(var i=0;i<dataArray.length;i++){
                console.log(dataArray);
                data[dataArray[i].name] = dataArray[i].value;
            }
            return data;
        }

but I want to make it like:

[
    { "sku": "EC1000-WMK", "qty": "1" }
    { "sku": "POP-11", "qty": "1" }
]
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Use Input fields name be like

<input name="item.0.sku" />
<input name="item.0.qty" />
<input name="item.1.sku" />
<input name="item.2.qty" />

& then use this function Here is the function which converts all form inputs to JSON format

const jsonSerialize = ($this) => {
    $this = $this.find('input, select');
    let data = {};
    for (let i = 0; i < $this.length; i++) {
        let el = $this[i];
        let val = el.value;
        if (!val) val = "";
        let fullName = el.getAttribute("name");
        if (!fullName) continue;
        let fullNameParts = fullName.split('.');
        let prefix = '';
        let stack = data;
        for (let k = 0; k < fullNameParts.length - 1; k++) {
            prefix = fullNameParts[k];
            if (!stack[prefix]) {
                stack[prefix] = {};
            }
            stack = stack[prefix];
        }
        prefix = fullNameParts[fullNameParts.length - 1];
        if (stack[prefix]) {
            let newVal = stack[prefix] + ',' + val;
            stack[prefix] += newVal;
        } else {
            stack[prefix] = val;
        }
    }
    return data
}

let $form = $('form');
params = jsonSerialize($form)

Hope may this work for you

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda