gpt4 book ai didi

javascript - 对象属性为 null,但输入的值不是 null。如何正确插入值?

转载 作者:行者123 更新时间:2023-12-01 00:06:22 24 4
gpt4 key购买 nike

这是初始状态,我尝试在每年和每个速度之前添加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。变量越少,代码就越稳定。

关于javascript - 对象属性为 null,但输入的值不是 null。如何正确插入值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60353218/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com