我有一个如下所示的数据对象:
costByLob:
[
{"key":"Retail","values":[
{"key":"2015-05","values":1},
{"key":"2015-06","values":1},
{"key":"2015-07","values":1},
{"key":"2015-08","values":1},
{"key":"2015-09","values":1},
{"key":"2015-10","values":1},
{"key":"2015-11","values":1},
{"key":"2015-12","values":1},
{"key":"2016-01","values":1},
{"key":"2016-02","values":1},
{"key":"2016-03","values":1},
{"key":"2016-04","values":1},
{"key":"2016-05","values":1},
{"key":"2016-06","values":1},
{"key":"2016-07","values":1},
{"key":"2016-08","values":1},
]
}
]
我尝试使用"key"
将YYYY-MM
从new date()
转换为数字日期版本。
我可以循环遍历整个对象,然后将其重新组合在一起,但有更简单的方法可以循环使用吗?
答案 0 :(得分:3)
正如其他人所说,你必须以某种方式循环。但是,Array.prototype.map函数可以使您的代码更简洁:
costByLob = [
{"key":"Retail","values":[
{"key":"2015-05","values":1},
{"key":"2015-06","values":1},
{"key":"2015-07","values":1},
{"key":"2015-08","values":1},
{"key":"2015-09","values":1},
{"key":"2015-10","values":1},
{"key":"2015-11","values":1},
{"key":"2015-12","values":1},
{"key":"2016-01","values":1},
{"key":"2016-02","values":1},
{"key":"2016-03","values":1},
{"key":"2016-04","values":1},
{"key":"2016-05","values":1},
{"key":"2016-06","values":1},
{"key":"2016-07","values":1},
{"key":"2016-08","values":1},
]
}
];
costByLob[0]["values"].map(function(data){
data["key"] = new Date(data["key"]).getTime();
return data;
});
console.log(JSON.stringify(costByLob, '', 2))