我有一个像这样的对象:
{ '2018':
{ '12':
{ '25': {},
'26': {},
'27': {},
'28': {},
'29': {},
'30': {},
'31': {} } },
'2019': { '1': { '1': {} } } }
但是出于前端目的,我想反转这些值,以便它首先显示最近的日期。我知道Javascript无法保证键的顺序,因此这甚至不是理想的解决方案。表示此数据的最佳方法是什么,以便我可以在前端对其进行迭代并正确显示每天的数据?谢谢
答案 0 :(得分:0)
reverse()方法将数组反转到位。第一个数组元素成为最后一个,最后一个数组元素成为第一个。
var array1 = ['one', 'two', 'three'];
console.log('array1: ', array1);
// expected output: Array ['one', 'two', 'three']
var reversed = array1.reverse();
console.log('reversed: ', reversed);
// expected output: Array ['three', 'two', 'one']
/* Careful: reverse is destructive. It also changes
the original array */
console.log('array1: ', array1);
// expected output: Array ['three', 'two', 'one']
OR
//non recursive flatten deep using a stack
var arr1 = [1,2,3,[1,2,3,4, [2,3,4]]];
function flatten(input) {
const stack = [...input];
const res = [];
while (stack.length) {
// pop value from stack
const next = stack.pop();
if (Array.isArray(next)) {
// push back array items, won't modify the original input
stack.push(...next);
} else {
res.push(next);
}
}
//reverse to restore input order
return res.reverse();
}
flatten(arr1);// [1, 2, 3, 1, 2, 3, 4, 2, 3, 4]