在JavaScript转换数组对象到另一个对象 - 第2部分 [英] Converting an array object to another object-Part 2 in javascript
本文介绍了在JavaScript转换数组对象到另一个对象 - 第2部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是一个跟进的问题<一href=\"http://stackoverflow.com/questions/32784004/converting-an-object-to-an-array?noredirect=1#comment53406918_32784004\">Converting一个对象到数组
。现在我希望做一个逆向工程,我想给JOSN转换回原来的格式除了它的一个对象,像如下面的例子。
VAR数据1 = [
{
名:煤
值:2
时代:2015年11月31日00:00:00
级别:10
},
{
名:页岩
值:4,
时代:2015年10月31日00:00:00
级别:20
}]
到
VAR数据2 =
{
煤:{
2015年9月:2
级别:10
},
页岩:{
2015年10月:4,
级别:20 }
}
其中结果是一个对象,不是一个人array.Can请帮助我在这个问题上
解决方案
函数yymmddToString(YYMMDD){
VAR个月= ['月','月','月','月'......]
变种X = yymmdd.split(' - ');
返回月[parseInt函数(X [1],10)] +''+ X [0];
}
VAR的结果= data1.reduce(功能(结果,基准){
VAR X =结果[datum.name] =结果[datum.name] || {};
×〔yymmddToString(datum.time)] = datum.value;
返回结果;
},{});
This is a follow up question of Converting an object into array .Now I would like to do a reverse engineering where I want to convert back the JOSN to the original format except its a object ,like as shown in the example below.
var data1=[
{
"name": "Coal",
"value": "2",
"time": "2015-11-31 00:00:00",
"level":"10"
},
{
"name": "Shale",
"value": "4",
"time": "2015-10-31 00:00:00",
"level":"20"
}
]
to
var data2=
{
"Coal": {
"September 2015": "2",
"level":"10"
},
"Shale": {
"October 2015": "4",
"level":"20"
}
}
where the result is an object not an array.Can anyone pls help me on this issue
解决方案
function yymmddToString(yymmdd) {
var months = ['January', 'February', 'March', 'April' .....];
var x = yymmdd.split('-');
return months[parseInt(x[1], 10)] + ' ' + x[0];
}
var result = data1.reduce(function(result, datum) {
var x = result[datum.name] = result[datum.name] || {};
x[yymmddToString(datum.time)] = datum.value;
return result;
}, {});
这篇关于在JavaScript转换数组对象到另一个对象 - 第2部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文