我有一个现有的数组,我想在JS中重新格式化。这是现有的数组,其中每个项目都是一个对象:
[
{
end_time:"7.14",
pk:45065,
start_time:"4.51",
text:"Lorem Ipsum"
},
{
end_time:"9.00",
pk:45066,
start_time:"7.14",
text:"Lorem Ipsum Something"
},
{
end_time:"13.09",
pk:450667 ,
start_time:"9.00",
text:"Lorem Ipsum Something"
},
{
end_time:"17.01",
pk:45068,
start_time:"13.09",
text:"Lorem Ipsum"
},
{
end_time:"25.10",
pk:45069,
start_time:"17.01",
text:"Lorem Ipsum Something"
},
{
end_time:"28.06",
pk:450670 ,
start_time:"25.10",
text:"Lorem Ipsum Something"
},
]
我想创建一个新的对象数组,其中旧数组中的每三个对象都成为新数组中的一个对象,如下所示:
[
segment: {
phrase: {
end_time:"7.14",
pk:45065,
start_time:"4.51",
text:"Lorem Ipsum"
},
phrase: {
end_time:"9.00",
pk:45066,
start_time:"7.14",
text:"Lorem Ipsum Something"
},
phrase: {
end_time:"13.09",
pk:450667 ,
start_time:"9.00",
text:"Lorem Ipsum Something"
}
},
segment {
phrase: {
end_time:"17.01",
pk:45068,
start_time:"13.09",
text:"Lorem Ipsum"
},
phrase: {
end_time:"25.10",
pk:45069,
start_time:"17.01",
text:"Lorem Ipsum Something"
},
phrase: {
end_time:"28.06",
pk:450670 ,
start_time:"25.10",
text:"Lorem Ipsum Something"
},
}
]
我最挣扎的是如何拉出每三个项目并推送到地图或循环中的新段对象我猜。我不确定最有效的方法。非常感谢任何帮助。
答案 0 :(得分:0)
Reduce函数从新对象内的json
数组中删除每个对象,其中key
是短语,其值是指定对象。然后,只需将结果分配给新创建的对象作为段键的值。
var json = [{end_time:"7.14",pk:45065,start_time:"4.51",text:"Lorem Ipsum"},{end_time:"9.00",pk:45066,start_time:"7.14",text:"Lorem Ipsum Something"},{end_time:"13.09",pk:450667,start_time:"9.00",text:"Lorem Ipsum Something"},{end_time:"17.01",pk:45068,start_time:"13.09",text:"Lorem Ipsum"},{end_time:"25.10",pk:45069,start_time:"17.01",text:"Lorem Ipsum Something"},{end_time:"28.06",pk:450670,start_time:"25.10",text:"Lorem Ipsum Something"}],
res = json.reduce(function(s,a){
obj = {};
obj.phrase = a;
s.push(obj);
return s;
}, []);
var object = {};
object.segment = res;
var result = [object];
console.log(result);
答案 1 :(得分:0)
var arr = [
{
end_time:"7.14",
pk:45065,
start_time:"4.51",
text:"Lorem Ipsum"
},
{
end_time:"9.00",
pk:45066,
start_time:"7.14",
text:"Lorem Ipsum Something"
},
{
end_time:"13.09",
pk:450667 ,
start_time:"9.00",
text:"Lorem Ipsum Something"
},
{
end_time:"17.01",
pk:45068,
start_time:"13.09",
text:"Lorem Ipsum"
},
{
end_time:"25.10",
pk:45069,
start_time:"17.01",
text:"Lorem Ipsum Something"
},
{
end_time:"28.06",
pk:450670 ,
start_time:"25.10",
text:"Lorem Ipsum Something"
},
];
var obj = {};
arr.forEach(arrayTransformClosure(obj));
document.getElementById('output').innerHTML = JSON.stringify(obj, null, 2);
// Functions
function arrayTransformClosure(obj) {
var phrase = 0;
var segment = 1;
return function (elem) {
++phrase;
if (phrase == 1) {
obj['segment_' + segment] = {
['phrase_' + phrase]: elem
};
} else if (phrase <= 3) {
obj['segment_' + segment]['phrase_' + phrase] = elem;
} else {
phrase = 1;
++segment;
obj['segment_' + segment] = {
['phrase_' + phrase]: elem
};
}
};
}
&#13;
<pre id="output"></pre>
&#13;