简体   繁体   English

更改数组javascript的格式

[英]change format of a array javascript

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. 想法是将array2放置为等于array1,我的意思是方括号和逗号的格式。

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}]

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]; }); 

The most appropriate way to do this is probably using the map() method. 最合适的方法可能是使用map()方法。 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]]

"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: 这是简短的ES6解决方案:

 var array1 = [["Sep",687918],["Nov",290709],["Dic",9282],["Ene",234065]]; var newArray = []; array1.forEach(item => newArray.push({[item[0]]: item[1]})) console.log(newArray) 

You can do this by using the array .reduce method: 您可以使用array .reduce方法执行此操作:

 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) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM