反转对象层次结构

有没有办法在js中反转对象?

想做一个功能,但苦苦挣扎。我尝试先找到对象深度,然后在对象内部对 .. in .. 进行一定数量的迭代,但不知道如何重写新的

const initObject = { 
  value: 5,
  next: {
   value: 10,
   next: {
     value: 15
     next: null
   }
  },
}

//expected result

const newObject = {
  value: 15,
  next: {
    value: 10,
    next: {
      value: 5,
      next: null
    }
  }
}

回答

您可以使用递归函数来收集所有值。然后使用reduce从值创建嵌套对象:

const initObject = { 
  value: 5,
  next: {
   value: 10,
   next: {
     value: 15,
     next: null
   }
  }
}

const getValues = ({ value, next }) =>
  next 
    ? [value, ...getValues(next)] 
    : [value]

const createObject = values => 
  values.reduce((next, value) => ({ value, next }), null)

const output = createObject(getValues(initObject))

console.log(output)


以上是反转对象层次结构的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>