Javascript:在对象数组中创建新列
2019-02-20
2806
我有一个对象数组,如下所示:
var arr1 = [
{"Date": "2017-04-15", "Price":"300"},
{"Date": "2017-04-16", "Price":"310"},
{"Date": "2017-04-17", "Price":"320"},
]
我希望在每一行中添加一个新的键(
newDate
)-值(JS
Date
对象)对。也就是说,我希望最终得到:
[
{"newDate":2017-04-14T14:00:00.000Z, "Date": "2017-04-15", "Price":"300"},
{"newDate":2017-04-15T14:00:00.000Z, "Date": "2017-04-16", "Price":"310"},
{"newDate":2017-04-16T14:00:00.000Z, "Date": "2017-04-17", "Price":"320"},
]
到目前为止,我在
node
中运行的脚本:
function getDateObject(dateString) {
// Splits a yyyy-mm-dd string, and returns a Date object
var parts = dateString.split("-")
var myDate = new Date(parts[0], parts[1]-1, parts[2])
return myDate
for (var i = 0; i < arr1.length; i++) {
console.log(arr1[i])
arr1[i]["newDate"] = getDateObject(arr1[i]["Date"])
}
这会出现错误:
TypeError: Cannot read property 'split' of undefined at getDateObject
也就是说,它在行
var parts = dateString.split("-")
处抛出错误。我对这个语法错误感到困惑,因为
dateString
当然没有定义;它应该是一个输入参数,而不是由
var
、
let
或
const
或其他东西实例化的变量。我遗漏了什么吗?
额外福利:如果有人能建议使用
array.map
来实现这一点,那就太好了。
3个回答
另一个解决方案可能是使用
Array.map()
和
destructuring
:
var arr1 = [
{"Date": "2017-04-15", "Price":"300"},
{"Date": "2017-04-16", "Price":"310"},
{"Date": "2017-04-17", "Price":"320"},
];
console.log( arr1.map(o => ({newDate: new Date(o.Date), ...o})) );
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}
或者,如果您不介意更改原始
array
,则使用
Array.forEach()
:
var arr1 = [
{"Date": "2017-04-15", "Price":"300"},
{"Date": "2017-04-16", "Price":"310"},
{"Date": "2017-04-17", "Price":"320"},
];
arr1.forEach(o => o.newDate = new Date(o.Date));
console.log(arr1);
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}
Shidersz
2019-02-20
arr1
是对象数组,而不是数组数组。仅当您尝试从被迭代对象的第 0 个属性获取某些内容时,引用
arr1[i][0]
才有意义,但不存在这样的属性,因此
undefined
。改为传递
arr[i].date
:
var arr1 = [
{"Date": "2017-04-15", "Price":"300"},
{"Date": "2017-04-16", "Price":"310"},
{"Date": "2017-04-17", "Price":"320"}
]
function getDateObject(dateString) {
// Splits a yyyy-mm-dd string, and returns a Date object
var parts = dateString.split("-")
var myDate = new Date(parts[0], parts[1]-1, parts[2])
return myDate
}
for (var i = 0; i < arr1.length; i++) {
arr1[i]["newDate"] = getDateObject(arr1[i].Date)
}
console.log(arr1);
或者,使用
.map
:
var arr1 = [
{"Date": "2017-04-15", "Price":"300"},
{"Date": "2017-04-16", "Price":"310"},
{"Date": "2017-04-17", "Price":"320"}
];
const arr2 = arr1.map((obj) => {
const [y, m, d] = obj.Date.split('-');
return { ...obj, newDate: new Date(y, m - 1, d) };
});
console.log(arr2);
CertainPerformance
2019-02-20
我认为您需要在 for 循环中访问
“日期”
而不是
0
arr1[i]["newDate"] = getDateObject(arr1[i]["Date"])
// or
arr1[i].newDate = getDateObject(arr1[i].Date)
M. Daw
2019-02-20