首页 > 解决方案 > 从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
        }
    });
}

如果有人可以帮助我,我将不胜感激。

标签: javascriptrecursionnested-object

解决方案


而不是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
}


推荐阅读