javascript - 反转对象层次结构
问题描述
有什么办法可以反转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)
推荐阅读
- r - 提取列表中的列表以在 R 中构建数据框
- prestashop - 在 Prestashop 1.7.1.1 中使用 addJS 时未添加 JS
- python - 如何在Python中对包括整数的字符串列表进行排序
- angular - Firebase Firestore 如何查询子集合
- android - android RecyclerView 崩溃
- wordpress - woocommerce 产品变体,将下拉列表移至变体名称下方
- javascript - 使用 React JS 在所有段落中添加 SPAN 元素
- vue.js - Vuepress 链接和脚本标签在开发模式下不起作用
- python - 使用 SQL Server 2017 机器学习服务使用 Python 构建预测模型
- javascript - 如何使用将 Observable 映射到值是 observable 的对象的函数来映射 Observable?