Convert object array to array arrays

Asked

Viewed 13,554 times

10

How to perform string conversion (object array):

 [
  {"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 (Component of the EXTJS library)

  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, correct? But I need to create the data for this array dynamically, because these will only come in the form of string, it is not possible for me to bring data via database, the tool I work with limits me.

3 answers

15


Here is a version with native Javascript, it is very simple:

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

jsFiddle: https://jsfiddle.net/8k3o1v80/

The code has two .map(). The first is because you start with an array (of objects), and you want to maintain 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 to the callback of that .map() the value of that key: obj[chave].

  • 1

    Thanks Sergio, helped me a lot. Thank you for helping me in my work.

  • @durtto I’m glad I helped.

3

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);
  • 1

    thanks for your attention.

1

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)

Browser other questions tagged

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