【问题标题】:How to reverse nested object in Javascript [duplicate]如何在Javascript中反转嵌套对象[重复]
【发布时间】:2019-01-03 13:36:55
【问题描述】:

我有一个这样的对象:

{ '2018':
   { '12':
      { '25': {},
        '26': {},
        '27': {},
        '28': {},
        '29': {},
        '30': {},
        '31': {} } },
  '2019': { '1': { '1': {} } } }

但是出于前端目的,我想反转这些值,以便它首先显示最近的日期。我知道 Javascript 不能保证键的顺序,所以这甚至不是一个理想的解决方案。表示这些数据的最佳方式是什么,以便我可以在前端对其进行迭代并正确显示每天的数据?谢谢

【问题讨论】:

  • 请分享预期的结构。
  • @Robert Harvey,这个问题不涉及嵌套数据,此外 Javascript 不保证顺序,所以它甚至不是一个真正的答案
  • @RoberHarvey 您确实将此问题链接到另一个与对象中键的顺序相关联的封闭问题。也许他的目标是无论如何都有一个由相反顺序的对象组成的还原结构(作为一个数组)
  • @quirimmo 我实际上已经设计了一个解决方案,一旦我确认它有效,我会发布它

标签: javascript arrays node.js object


【解决方案1】:

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']

//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]

【讨论】:

  • 这不是一个数组。
  • 是数组请重新检查
猜你喜欢
  • 1970-01-01
  • 2021-12-29
  • 1970-01-01
  • 2020-10-08
  • 1970-01-01
  • 2021-08-16
  • 1970-01-01
  • 2011-12-26
  • 1970-01-01
相关资源
最近更新 更多