0

How can I change the format of the array? the idea is to place the array2 equal to the array1, I mean the format of square brackets and commas.

that is, change the ":" with "," and the {} with []

var array1=[["Sep",687918],["Nov",290709],["Dic",9282],["Ene",234065]]


var array2=[{"Sep":687918},{"Nov":290709},{"Dic":9282},{"Ene":348529}]

4 Answers4

0

This work for you?

var array1=[["Sep",687918],["Nov",290709],["Dic",9282],["Ene",234065]];
var array2 = {};
array1.forEach(function(element){
  array2[element[0]]=element[1];
});
0

The most appropriate way to do this is probably using the map() method. Using this, you're constructing a new array by manipulating each item of an original array. Learn more here.

var array2=[{"Sep":687918},{"Nov":290709},{"Dic":9282},{"Ene":348529}];

var array1 = array2.map(function (item) {
  var key = Object.keys(item)[0];
  var value = item[key];
  return [key, value];
});

console.log(array1);

// returns [["Sep", 687918], ["Nov", 290709], ["Dic", 9282], ["Ene", 348529]]
Alex MacArthur
  • 2,220
  • 1
  • 18
  • 22
0

"I mean the format of square brackets and commas"

Square brackets says, that it is an array, and array elements should be separated by commas. Actually, you want to convert the array of arrays to the array of objects. Here is short ES6 solution:

var array1 = [["Sep",687918],["Nov",290709],["Dic",9282],["Ene",234065]];
var newArray = [];

array1.forEach(item => newArray.push({[item[0]]: item[1]}))
console.log(newArray)
P.S.
  • 15,970
  • 14
  • 62
  • 86
0

You can do this by using the array .reduce method:

var array1=[["Sep",687918],["Nov",290709],["Dic",9282],["Ene",234065]]

var array2 = array1.reduce((arr2, current) => { 
    arr2.push({[current[0]]: current[1]});
    return arr2
}, []);

console.log(array2)
CRice
  • 29,968
  • 4
  • 57
  • 70