JS - Array of objects for array array

7

How do I convert an array of objects to an array of arrays in javascript? I did this, but it returns an array of objects

var items1 = new Array();


 $.map(objResposta, function(value,index) {
       teste = new Array();
       items1.push(value);
       teste.push(items1);

 });

I need the values that are in red to stay in the array this way:

Array [ ['resposta atualizada', 5], ['esse foi', 4] ]
Is there any way to popular this way?

    
asked by anonymous 19.12.2016 / 13:45

3 answers

10

You already have an array ... an array of objects, you have to convert to an array of arrays.

You can do it like this:

const array = [{
    nomePergunta: 'resposta atualizada',
    quantidadeResposta: 5
}, {
    nomePergunta: 'esse foi',
    quantidadeResposta: 4
}];

const novaArray = array.map(el => Object.keys(el).map(key => el[key]));

console.log(JSON.stringify(novaArray));

The idea is:

  • past initial array
  • converts each object into an array of its keys / properties
  • maps this array of each object to the values of those keys

Like Mr. Felix mentioned in the ES7 version there is a new method for Objects, the Object.values . In this case it's even simpler:

 const novaArray = array.map(Object.values);

Example:

const array = [{
  nomePergunta: 'resposta atualizada',
  quantidadeResposta: 5
}, {
  nomePergunta: 'esse foi',
  quantidadeResposta: 4
}];

const novaArray = array.map(Object.values);

console.log(JSON.stringify(novaArray));
    
19.12.2016 / 13:50
6

With the ECMAScript 2017+ you can do the following:

var arrays = objetos.map(function(obj){return Object.values(obj)});

Being objetos is your array of objects.

Chrome version 55, for example, already works.

As a suggestion for @Sergio ♦, you can simplify it even more:

var arrays = objetos.map(Object.values);
    
19.12.2016 / 14:05
2

Another approach is to use a classic iterator (although I prefer map), read the properties of the object, add in a temporary array to add to the new array of arrays:

var array = [{
    nomePergunta: 'resposta atualizada',
    quantidadeResposta: 5
}, {
    nomePergunta: 'esse foi',
    quantidadeResposta: 4
}];

var novoArray = [];

array.forEach(function(item){
  var tmp = [];
  for (var property in item){
    tmp.push(item[property]);
  }
  novoArray.push(tmp);
});

console.log(JSON.stringify(novoArray));
    
19.12.2016 / 14:02