首页 > 解决方案 > 反转对象层次结构

问题描述

有什么办法可以反转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
    }
  }
}

标签: javascript

解决方案


您可以使用递归函数来收集所有值。然后用于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)


推荐阅读