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

Time:09-29

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)

I have wrote a recursive function that should replace each key-value pair (not property!) with a object that i specify in the parameter.

However, if I use a array.forEach loop inside the function, the passed obj is undefined.

What am I missing?

Example


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);
    }
    })
}

However, if I define the object within the forEach, it works perfectly ....

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);
    }
    })
}

Why does the Object.keys(obj).forEach not see the passed parameter in the first version? And what is the solution?

CodePudding user response:

You need to pass newObj whenever you call iterate inside the Array.forEach() - iterate(obj[key], 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)

  • Related