Convert array of objects to array of arrays

8

How to perform string conversion (array of objects):

 [
  {"id":1,"nome":"Maluf","cpf":"007.519.591-20"},
  {"id":2,"nome":"Paulo Ricardo","cpf":"565.232.591-02"},
  {"id":3,"nome":"Joaquim Barbosa","cpf":"007.519.699-32"}, 
  {"id":4,"nome":"Dilma Folgada","cpf":"007.963.000-02"}
 ]

For an array of arrays:

[
  [1,'Maluf','007.519.591-20'],
  [2,'Paulo Ricardo','565.232.591-02'],
  [3,'Joaquim Barbosa','007.519.699-32'], 
  [4,'Dilma Folgada','007.963.000-02']
 ]
  

Note: Note that in the expected result I do not have the attributes. id, name, cpf

Explaining the Situation:

I have a component Ext.data.ArrayStore (EXTJS library component)

  var dependentes = new Ext.data.ArrayStore({
    fields: [
      {name: 'id'},
      {name: 'nomeDependente'},
      {name: 'cpfDependente'}
    ]
  });

And I have an array like this:

  var dados = [
    [1, Eduardo, '007.519.591-70'],
    [2, 'Fabio', '222.519.111-70']
  ];

The array data is fixed, right? But I need to dynamically create the data from this array, because these will only come in the form of a string, I can not bring the data via the database, the tool that I work with limits me.

    
asked by anonymous 29.12.2015 / 17:15

3 answers

13

Here is a version with native JavaScript, it's very simple:

var convertida = original.map(function(obj) {
    return Object.keys(obj).map(function(chave) {
        return obj[chave];
    });
});

jsFiddle: link

The code has two .map() . The first is because you start with an array (of objects), and you want to keep an array with the same number of elements. The second .map() is to transform / map each object into an array. And you can do this by returning the callback of this .map() the value of that key: obj[chave] .

    
29.12.2015 / 17:35
2

Take a look at this algorithm, see if it helps.

  var objArr = []; //Array final
  var myObj = [
    {"id":1,"nome":"Maluf","cpf":"007.519.591-20"},
    {"id":2,"nome":"Paulo Ricardo","cpf":"565.232.591-02"},
    {"id":3,"nome":"Joaquim Barbosa","cpf":"007.519.699-32"}, 
    {"id":4,"nome":"Dilma Folgada","cpf":"007.963.000-02"}
   ];

   //Aqui percorremos seu obj inicial e criamos o conteudo do array final
   $.each(myObj,function(idx,obj){
    objArr.push([obj.id,obj.nome,obj.cpf]);  
   });

   //Output com resultado no console
   console.info('Seu objeto array', objArr);
    
29.12.2015 / 17:26
0

Simplifying a little more !!

var vetor = [
  {"id":1,"nome":"Maluf","cpf":"007.519.591-20"},
  {"id":2,"nome":"Paulo Ricardo","cpf":"565.232.591-02"},
  {"id":3,"nome":"Joaquim Barbosa","cpf":"007.519.699-32"}, 
  {"id":4,"nome":"Dilma Folgada","cpf":"007.963.000-02"}
].map(item => [item.id,item.nome,item.cpf])

console.log(vetor)
    
02.03.2018 / 14:34