JavaScript:参数未传递给函数内部的 Array.forEach => 未定义?

JavaScript: Parameter not passed to Array.forEach inside of the function => undefined?

const data = {
  "desk": {
    "drawer": "stapler"
  },
  "cabinet": {
    "top drawer": { 
      "folder1": "a file",
      "folder2": "secrets"
    },
    "bottom drawer": "soda"
  },
  "item" : [
    {
      "hello" : {
        "world" : "isHere"
      },
      "test" : "1"
    },
        {
      "hello" : {
        "world" : "isHere2"
      },
      "test" : "2"
    },
    ]
};

const iterate = (obj) => {
  
    Object.keys(obj).forEach(key => {

    if (typeof obj[key] === 'object') {
            iterate(obj[key])
    } else{
        let value = obj[key];
        let newObj = {[key]: value, 'style' : {backGroundColor : 'red'}};
        delete obj[key];
        Object.assign(obj, newObj);
    }
    })
}

iterate(data);
console.log(data)

我写了一个递归函数,它应该用我在参数中指定的对象替换每个键值对(不是 属性!)。

但是,如果我在函数内部使用 array.forEach 循环,传递的 obj未定义.

我错过了什么?

例子


const iterate = (obj, newObj) => {

    Object.keys(obj).forEach(key => {

    if (typeof obj[key] === 'object') {
            iterate(obj[key])
    } else{
        delete obj[key];
        Object.assign(obj, newObj);
    }
    })
}

但是,如果我在 forEach 中定义对象,它会完美地工作....

const iterate = (obj) => {

    Object.keys(obj).forEach(key => {

    if (typeof obj[key] === 'object') {
            iterate(obj[key])
    } else{
        let value = obj[key];
        
        // SEE HERE
        let newObj = {[key]: value, 'style' : {backGroundColor : 'red'}};

        delete obj[key];
        Object.assign(obj, newObj);
    }
    })
}

为什么第一个版本的Object.keys(obj).forEach看不到传递的参数? 解决方案是什么?

每当您在 Array.forEach() - iterate(obj[key], newObj):

中调用 iterate 时,您需要传递 newObj

const data = {"desk":{"drawer":"stapler"},"cabinet":{"top drawer":{"folder1":"a file","folder2":"secrets"},"bottom drawer":"soda"},"item":[{"hello":{"world":"isHere"},"test":"1"},{"hello":{"world":"isHere2"},"test":"2"}]};

const iterate = (obj, newObj) => {
  Object.keys(obj).forEach(key => {
    if (typeof obj[key] === 'object') {
      iterate(obj[key], newObj)
    } else {
      // delete obj[key]; // remove for example purposes
      Object.assign(obj, newObj);
    }
  })
}

const newObj = {
  'style': {
    backGroundColor: 'red'
  }
};

iterate(data, newObj);
console.log(data)