javascript - 从javascript中的其他对象递归地创建一个嵌套对象
问题描述
我是编程新手,我正在研究一个困扰我一段时间的问题。
我想从javascript中的另一个嵌套对象递归地创建一个嵌套对象,
下面是输入的示例数据,但在实际情况下,我不知道这个对象有多深。
nums = {
Obj:{
x1:{
x11:43,
x12:4,
x13:612
},
x2:{
x21:4,
x22:7,
},
x3:2,
}}
这是我想要的结果(见数字是偶数还是奇数,偶数=真,奇数=假)
res = {
Obj:{
x1:{
x11:false,
x12:true,
x13:true
},
x2:{
x21:true,
x22:false,
},
x3:true,
}}
这是我的代码
const nums = {
Obj:{
x1:{
x11:43,
x12:4,
x13:612
},
x2:{
x21:4,
x22:7,
},
x3:2,
}
}
const res ={};
getResult(nums);
console.log(res);
function getResult(x){
Object.keys(x).forEach(element => {
if(isNaN(x[element])){
res[element]=getResult(x[element]);
} else {
let result = (x[element] % 2 < 1)? true:false;
return {[element]: result}; // this is where I don't know what to, I try to return a object,
// but it gives{x1: undefined, x2: undefined, Obj: undefined}
//
// if I change to "return res[element]=result"
// every sub-Object will add under the same level
}
});
}
如果有人可以帮助我,我将不胜感激。
解决方案
而不是return {[element]: result};
覆盖值,并在循环之后从函数返回变异对象:
请注意,这会改变原始对象,如果要保留它,请复制:
const copy = JSON.parse(JSON.stringify(nums));
const nums = {
Obj: {
x1: {
x11: 43,
x12: 4,
x13: 612
},
x2: {
x21: 4,
x22: 7,
},
x3: 2,
}
}
const res = {};
const copy = JSON.parse(JSON.stringify(nums));
getResult(copy);
console.log(res);
function getResult(x) {
Object.keys(x).forEach(element => {
if (isNaN(x[element])) {
res[element] = getResult(x[element]);
} else {
let result = (x[element] % 2 < 1) ? true : false;
x[element] = result; // overwrite the number with true or flse
}
});
return x; // return the mutated object
}
推荐阅读
- javascript - 网格 div 和 js 滚动动画的一种背景
- c - 在记事本中打开 C 程序创建的文本文件时显示错误
- javascript - 为什么 time() 和 Date.now 给出不同的结果?
- docker - 在 Azure Functions 的 Docker 容器中编译 Pixar 的 USD
- hive - 如何从 hive 获取最新的分区数据
- flutter - Flutter webviews 给出 net::ERR_CACHE_MISS 消息
- c# - 扫描的项目(UWP 应用)不显示在 ListBox 中
- android - 找不到 com.android.tools.build:gradle:2.2.0
- javascript - React Ant 表自定义列计算。如何获取每行中其他项目的长度
- r - 在 R 中绘图时使用点