JS - mapping string into array of objects ¿How to change key name?

Viewed 146

$(document).ready(function() {
 printData("customerNumber>103#customerName>Atelier graphique#contactLastName>Schmitt#contactFirstName>Carine #phone>40.32.2555#addressLine1>54, rueRoyale#addressLine2>#city>Nantes#state>#postalCode>44000#country>France#salesRepEmployeeNumber>1370#creditLimit>21000#~customerNumber>112#customerName>Signal Gift Stores#contactLastName>King#contactFirstName>Jean#phone>7025551838#addressLine1>8489 Strong St.#addressLine2>#city>LasVegas#state>NV#postalCode>83030#country>USA#salesRepEmployeeNumber>1166#creditLimit>71800#~customerNumber>114#customerName>Australian Collectors, Co.#contactLastName>Ferguson#contactFirstName>Peter#phone>03 9520 4555#addressLine1>636 St KildaRoad#addressLine2>Level3#city>Melbourne#state>Victoria#postalCode>3004#country>Australia#salesRepEmployeeNumber>1611#creditLimit>117300#~customerNumber>119#customerName>La Rochelle Gifts#contactLastName>Labrune#contactFirstName>Janine #phone>40.67.8555#addressLine1>67, rue des CinquanteOtages#addressLine2>#city>Nantes#state>#postalCode>44000#country>France#salesRepEmployeeNumber>1370#creditLimit>118200#~")
})

function printData(data){
 var customers = data
  .split('~')
  .map((i, e) => {
   return i
   .split('#')
   .map((i, el) => {
    return [i.split('>')[0],i.split('>')[1]];
   })

  });

 // $.each(customers, (i, el) => {
 //  customers[i] = el.split('#');
 //  $.each(customers[i], (name, valor) => {

 //  })
 // })

 console.log(customers);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

I get data from a source in a string like this:

prop1>value1#prop2>value2~
prop1>value1#prop2>value2~
prop1>value1#prop2>value2

where:

  • "~" splits rows
  • "#" splits columns
  • ">" splits propertie:value

this is the function i use to map it actually (where data is the string):

function printData(data){

    var customers = data
        .split('~')
        .map((i, e) => {
            return i
            .split('#')
            .map((i, el) => {
                return [i.split('>')[0],i.split('>')[1]];
            })
        });

    console.log(customers);
}

I almost got it, but i need a final help, this is what i get print at console:

enter image description here

And what i would like to get is something like

Array {
    customerNumber:103,
    customerName:Atelier
}

instead of:

Array{
    Array{
        0:customerNumber,
        1:103
    }
    Array{
        0:customerName,
        1:Atelier
    }
}

I explained it the best i can, hope it's enough!

1 Answers
Related