更改数组javascript的格式

时间:2018-01-10 19:27:06

标签: javascript

如何更改数组的格式?我的想法是将array2放在array1上,我的意思是方括号和逗号的格式。

即,将“:”改为“,”,将{}改为[]

<div style="display:flex;align-items: center;justify-content:space-between;height:100%;padding:1.25em;background-repeat: no-repeat;background-size: 100%;background-image: 
        url('data:image/svg+xml;utf8,<svg version=&quot;1&quot; xmlns=&quot;http://www.w3.org/2000/svg&quot; xmlns:xlink=&quot;http://www.w3.org/1999/xlink&quot; width=&quot;1024&quot; height=&quot;79&quot;><defs><path id=&quot;a&quot; d=&quot;M0 0h1024v79H0z&quot;/></defs><clipPath id=&quot;b&quot;><use xlink:href=&quot;%23a&quot; overflow=&quot;visible&quot;/></clipPath><linearGradient id=&quot;c&quot; gradientUnits=&quot;userSpaceOnUse&quot; x1=&quot;-4&quot; y1=&quot;35&quot; x2=&quot;1024&quot; y2=&quot;35&quot;><stop offset=&quot;0&quot; stop-color=&quot;%232377b8&quot;/><stop offset=&quot;1&quot; stop-color=&quot;%232e378e&quot;/></linearGradient><path clip-path=&quot;url(%23b)&quot; fill=&quot;url(%23c)&quot; d=&quot;M-4-9h1028v88H-4z&quot;/></svg>');">
<div style="display:flex;align-items:center;">
	<h1 style="margin:0;color:white;font-weight:bold;font-size:1.8em;line-height:1;">
    Title
    </h1>
    <h2 style="font-size:1.2em;line-height:1.5;color:white">
    &nbsp;| Dashboard
    </h2>
</div>
<div style="display:flex;align-items:center;">
	<h1 style="margin:0;color:white;font-weight:bold;font-size:1.8em;line-height:1;margin-right:15px;">Location</h1>
    <svg version="1" xmlns="http://www.w3.org/2000/svg" width="44" height="44"><circle cx="22" cy="22" r="22" fill="#fff"/>
        <circle cx="22" cy="22" r="19" fill="#0b694f"/><circle cx="23" cy="22" r="9" fill="#f02e46"/></svg>
</div>
</div>

4 个答案:

答案 0 :(得分:0)

这项工作适合你?

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

答案 1 :(得分:0)

最合适的方法是使用map()方法。使用此方法,您将通过操作原始数组的每个项目来构建新数组。了解详情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]]

答案 2 :(得分:0)

&#34;我的意思是方括号和逗号的格式&#34;

方括号表示它是一个数组,数组元素应该用逗号分隔。实际上,您希望将数组数组转换为对象数组。这是简短的ES6解决方案:

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

array1.forEach(item => newArray.push({[item[0]]: item[1]}))
console.log(newArray)
&#13;
&#13;
&#13;

答案 3 :(得分:0)

您可以使用数组.reduce方法执行此操作:

&#13;
&#13;
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)
&#13;
&#13;
&#13;