gpt4 book ai didi

javascript - 访问position[i]处的json元素并在map函数中更改它们的值

转载 作者:行者123 更新时间:2023-11-28 14:14:17 25 4
gpt4 key购买 nike

我有一个像这样的 json 文件

[
{
"label": "1556015903109.00",
"value1": "1.7481",
"value2": "1.7489",
"value3": "1.7375",
"value4": "2.5631"
},
{
"label": "1556015954378.00",
"value1": "1.7481",
"value2": "1.7336",
"value3": "1.7477",
"value4": "2.5631"
},
{
"label": "1556016004213.00",
"value1": "1.7481",
"value2": "1.7336",
"value3": "1.7426",
"value4": "2.5631"
},
{
"label": "1556016034313.00",
"value1": "1.7481",
"value2": "1.7489",
"value3": "1.7426",
"value4": "2.5631"
}
]

我正在尝试访问 label 下的所有元素,并将它们从 Unix 时间转换为日期时间,并使用新值更新数组

我构建了一个 map 函数,该函数应该访问元素并执行必要的数学魔法将其转换为正确的日期时间。

var json = json.map(function(a){
var dateT= '';
var changeUp = a.label.toString()
for(i=0; i <changeUp.length; i++){
var timestamp = changeUp[i]
var newStamp = timestamp /1000
var date = new Date(newStamp * 1000);
var hours = date.getHours();
var minutes = "0" + date.getMinutes();
var seconds = "0"+ date.getSeconds();
var formattedTime = hours +':' + minutes.substr(-2) +':' + seconds.substr(-2);
var dateT = date + ":" + formattedTime;
console.log(dateT);
changeUp[i] = dateT;
}

});

预期结果应该是

[
{
"label": "Sat April 27th 2019: 11:34:67 etc",
"value1": "1.7481",
"value2": "1.7489",
"value3": "1.7375",
"value4": "2.5631"
},
{
"label": "Proper Date Time",
"value1": "1.7481",
"value2": "1.7336",
"value3": "1.7477",
"value4": "2.5631"
},
{
"label": "Proper Date Time",
"value1": "1.7481",
"value2": "1.7336",
"value3": "1.7426",
"value4": "2.5631"
},
{
"label": "Proper Date Time",
"value1": "1.7481",
"value2": "1.7489",
"value3": "1.7426",
"value4": "2.5631"
}
]

相反,当我尝试调试时,它只是不断重新打印数组的元素或给我 NaN。

最佳答案

我发现你的代码有问题

  • map 回调中缺少返回值,
  • label 已经是一个字符串,无需再次调用 toString ,并且您会循环遍历字符串中的每个字符,因此最终会得到错误的结果<

您可以像这样简单地使用解构map

let data = [{"label": "1556015903109.00","value1": "1.7481","value2": "1.7489","value3": "1.7375","value4": "2.5631"},{"label": "1556015954378.00","value1": "1.7481","value2": "1.7336","value3": "1.7477","value4": "2.5631"},{"label": "1556016004213.00","value1": "1.7481","value2": "1.7336","value3": "1.7426","value4": "2.5631"},{"label": "1556016034313.00","value1": "1.7481","value2": "1.7489","value3": "1.7426","value4": "2.5631"}]

let final = data.map(({ label, ...rest }) => {
var newStamp = label / 1000
var date = new Date(newStamp * 1000);
var hours = date.getHours();
var minutes = "0" + date.getMinutes();
var seconds = "0" + date.getSeconds();
var formattedTime = hours + ':' + minutes.substr(-2) + ':' + seconds.substr(-2);
var dateT = date + ":" + formattedTime;
return {
...rest,
label: dateT
}
})

console.log(final)

关于javascript - 访问position[i]处的json元素并在map函数中更改它们的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58246980/

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