这是初始状态,我试图在每年和每种速度之前添加一个year:和speed:属性,并将所有对象添加到一个数组中以使用d3js处理。
{
2004: "226.933"
2005: "222.807"
2006: "221.869"
2007: "223.978"
2008: "218.385"
2009: "217.668"
2010: "216.061"
2011: "214.631"
2012: "214.053"
2013: "213.845"
2014: "206.436"
2015: "209.915"
2016: "214.51"
2017: "220.605"
2018: "222.128"
2019: "223.075"
}
我的代码创建对象数组
let arr = [];
let columns = ["year","speed"]
Object.entries(results).forEach(element => {
let imp = {};
let x = parseInt(element)
imp["year"] =parseInt(element[0]);
imp["speed"]=parseFloat(element[1]);
arr.push(imp);
});
console.log(arr);
这是我用控制台检查它时得到的
[
0: {year: null, speed: 226.933}
1: {year: null, speed: 222.807}
2: {year: null, speed: 221.869}
3: {year: null, speed: 223.978}
4: {year: null, speed: 218.385}
5: {year: null, speed: 217.668}
6: {year: null, speed: 216.061}
7: {year: null, speed: 214.631}
8: {year: null, speed: 214.053}
9: {year: null, speed: 213.845}
10: {year: null, speed: 206.436}
11: {year: null, speed: 209.915}
12: {year: null, speed: 214.51}
13: {year: null, speed: 220.605}
14: {year: null, speed: 222.128}
15: {year: null, speed: 223.075}
]
演示:
const results = {
2016: "214.51",
2017: "220.605",
2018: "222.128",
2019: "223.075",
}
let arr = [];
let columns = ["year", "speed"]
Object.entries(results).forEach(element => {
let imp = {};
let x = parseInt(element)
imp["year"] = parseInt(element[0]);
imp["speed"] = parseFloat(element[1]);
arr.push(imp);
});
console.log(arr);
Sourav的一个很接近,但map
内部不需要突变。map
返回一个新数组:
const data = {
2004: "226.933",
2005: "222.807",
2006: "221.869",
2007: "223.978",
2008: "218.385",
2009: "217.668",
2010: "216.061",
2011: "214.631",
2012: "214.053",
2013: "213.845",
2014: "206.436",
2015: "209.915",
2016: "214.51",
2017: "220.605",
2018: "222.128",
2019: "223.075",
};
const newArray = Object.entries(data)
.map(([year, speed]) => ({year, speed}))
console.log('data', data)
console.log('newArray', newArray)
另外,使用const
。变量越少,代码就越稳定。
试试这个:-
var data = {
2004: "226.933",
2005: "222.807",
2006: "221.869",
2007: "223.978",
2008: "218.385",
2009: "217.668",
2010: "216.061",
2011: "214.631",
2012: "214.053",
2013: "213.845",
2014: "206.436",
2015: "209.915",
2016: "214.51",
2017: "220.605",
2018: "222.128",
2019: "223.075",
};
var newArray = [];
Object.entries(data).map(function(item){
newArray.push({year:item[0], speed:item[1]})
})
console.log('data', data)
console.log('newArray', newArray)