Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can we modify nested object values without modifying original object in JavaScript?

How can I change all nested object values to "true" without using extra space Can anyone help me in this. I have tried in this way but I am not getting the logic to handle the nested object

P.S: Please don't concentrate about "true" or "false" is in string because it is mock data,I just want logic to implement which I am failing to do.

const config = {
  header:{"logo":"true","nav":"false","user":"false"},
  searchResults:{"listView":"false","favorite":"true","share":"false","pagination":"true","filters":"true","sortBy":"false"},
  sharedLinks:{},
  learnerLinks:{},
  lukePreview:{"toc":"false","controls":"false"},
  lukeLaunch:{"toc":"false","controls":"false"},
  misc:{"import":"true"}
}

function changeBoolean(obj,propName){
  for(let i in obj){
    if( typeof obj[i] === 'object'){
       changeBoolean(obj[i],i)
    }
  }
  return obj
}
console.log(changeBoolean(config,'header'))
like image 864
Akhil Raghav Avatar asked Jan 22 '26 11:01

Akhil Raghav


1 Answers

Try to assign the function's result, like this:


function changeBoolean(obj, propName) {
  for (let i in obj) {
    if (typeof obj[i] === "object") {
      obj[i] = changeBoolean(obj[i], propName);
    } else {
      obj[i] = "true";
    }
  }
  return obj;
}
like image 102
Owen Young Avatar answered Jan 24 '26 01:01

Owen Young



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!