将obj推入数组

时间:2018-07-12 21:55:38

标签: arrays object push

试图将obj推入数组

这是我拥有的代码:

for (var i = 0; i < arr2.length; i++) {
  var dates = [];
  dates.push(arr2[i].date);
}
console.log(dates);

这是数据:

var arr2 = [{"id":"1","exchange_symbol":"TSE","currency":"JPY","stock_id":"1","stock_name":"KYOKUYO CO.,LTD.","stock_symbol":"1301.T","date":"2006-12-29","time":"15:00:00.000000","close":"2388.023438000000000000","volume":"23700.000000000000000000","active":"1","exchange_id":"0"},{"id":"2","exchange_symbol":"TSE","currency":"JPY","stock_id":"1","stock_name":"KYOKUYO CO.,LTD.","stock_symbol":"1301.T","date":"2007-01-04","time":"15:00:00.000000","close":"2416.452637000000000000","volume":"16500.000000000000000000","active":"1","exchange_id":"0"},{"id":"3","exchange_symbol":"TSE","currency":"JPY","stock_id":"1","stock_name":"KYOKUYO CO.,LTD.","stock_symbol":"1301.T","date":"2007-01-05","time":"15:00:00.000000","close":"2369.071045000000000000","volume":"45400.000000000000000000","active":"1","exchange_id":"0"},{"id":"4","exchange_symbol":"TSE","currency":"JPY","stock_id":"1","stock_name":"KYOKUYO CO.,LTD.","stock_symbol":"1301.T","date":"2007-01-09","time":"15:00:00.000000","close":"2388.023438000000000000","volume":"28800.000000000000000000","active":"1","exchange_id":"0"}];

我很期待我的console.log(日期)看起来像这样:

"2006-12-29"
"2007-01-04"
"2007-01-05"
"2007-01-09"

但我明白了:

[Object {"id":"4","exchange_symbol":"TSE","currency":"JPY","stock_id":"1","stock_name":"KYOKUYO CO.,LTD.","stock_symbol":"1301.T","date":"2007-01-09","time":"15:00:00.000000","close":"2388.023438000000000000","volume":"28800.000000000000000000","active":"1","exchange_id":"0"}];

1 个答案:

答案 0 :(得分:0)

您的代码有两个问题:

1)结果数组在循环的每次迭代中重新初始化

2)您需要专门访问源对象的.date属性

var dates = [];

for (var i = 0; i < arr2.length; i++) {
  dates.push(arr2[i].date);
}

console.log(dates);

您可能还考虑了一些较慢但更优雅的方法:

var dates = arr2.map(e => e.date);
console.log(dates);