Javascript 如何动态在数组里添加对象?

后端发过来的数据格式是这样的:


var a = [

    { "title": "56岁及以上", "color": "#c12552", "value": "30", "sql": " select a00 from ipad_Analysis where s1='1' and  s10='硕士研究生及以上'" },

    { "title": "46岁至55岁", "color": "#ff6600", "value": "8", "sql": " select a00 from ipad_Analysis where  s1='1' and  s10='大学本科'" },

    { "title": "其他", "color": "#f5c700", "value": "13", "sql": " select a00 from ipad_Analysis where  s1='1' and  s10='大学专科'" }

];


由于我制作的界面使用了echart,所以必须把这个数组赋值给我的echartData中,如果只有着三条数据的话,那么写死就行了,



var echartData = [{

    value: parseInt(a[0].value),

    name: a[0].title

}, {

    value: parseInt(a[1].value),

    name: a[1].title

}, {

    value: parseInt(a[2].value),

    name: a[2].title

}

];

如果后端发过来的数据不止有三个对象,我怎么动态生成一个有多个对象(根据后端发过来的数据)的数组呢?


谢谢!


开心每一天1111
浏览 8490回答 5
5回答

慕后森

&nbsp;var a = [&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; { "title": "56岁及以上", "color": "#c12552", "value": "30", "sql": " select a00 from ipad_Analysis where s1='1' and&nbsp; s10='硕士研究生及以上'" },&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; { "title": "46岁至55岁", "color": "#ff6600", "value": "8", "sql": " select a00 from ipad_Analysis where&nbsp; s1='1' and&nbsp; s10='大学本科'" },&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; { "title": "其他", "color": "#f5c700", "value": "13", "sql": " select a00 from ipad_Analysis where&nbsp; s1='1' and&nbsp; s10='大学专科'" }&nbsp; &nbsp; &nbsp; &nbsp; ];&nbsp; &nbsp; &nbsp; &nbsp; let finalData = [];&nbsp; &nbsp; &nbsp; &nbsp; for(let i=0;i<a.length;i++){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; finalData.push({&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; value:parseInt(a[i].value),&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; name:a[i].title&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; })&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; console.dir(finalData);&nbsp; &nbsp;&nbsp;是不是这样的。

宝慕林4294392

写数据处理最好养成 map-reduce 的习惯,你这个需求在数据部分就是 map 过程原数组的数据结构到新目标结构是列表对列表,但具体对象有映射关系,大概是value --> parseInt(value),title --> name用 JS 的 map 来实现就是const echartData = a.map(x => ({&nbsp; &nbsp; value: parseInt(x.value),&nbsp; &nbsp; name: x.title});

守候你守候我

如下所示即可const echartData = a.map((item,index) => {&nbsp; &nbsp; return {&nbsp; &nbsp; &nbsp; &nbsp; value: parseInt(item.value),&nbsp; &nbsp; &nbsp; &nbsp; name: item.title&nbsp; &nbsp; }})

繁花不似锦

朋友,悄悄告诉你,有一个东西叫循环,非常棒。我从来没有告诉过别人,今天破例告诉你,记得替我保密!!

慕勒3428872

既然是个数组,难道你没听说过数组的push方法吗?循环遍历返回的数据,push进入数组不就ok了
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript