I have the below object and I wanted to toggle all the boolen value inside of the object
{
"2211284396232-5": {
"2211284396232-5": false,
"644889430161": {
"4812219518053": false,
"4812219518055": false,
"4812219518063": false,
"4812219518064": false,
"4812219518069": false,
"644889430161": false
},
},
"2211628865398-6": {
"2211628865398-6": false,
"729563966440": {
"5229922707373": false,
"729563966440": false
},
},
"2212485574058-4": {
"2212485574058-4": false,
"689399023594": {
"5077186698704": false,
"5077186698712": false,
"689399023594": false
},
},
}
I want to loop through this object and change all this false value to true value
How can I do this?
>Solution :
You can recursively examine each [key, value] entry in the object. You need to recurse when a property value is an object, and otherwise set the non-object properties to true.
const data = {"2211284396232-5":{"2211284396232-5":false,"644889430161":{"4812219518053":false,"4812219518055":false,"4812219518063":false,"4812219518064":false,"4812219518069":false,"644889430161":false}},"2211628865398-6":{"2211628865398-6":false,"729563966440":{"5229922707373":false,"729563966440":false}},"2212485574058-4":{"2212485574058-4":false,"689399023594":{"5077186698704":false,"5077186698712":false,"689399023594":false}}}
const f = obj => Object.entries(obj).forEach(([k, v]) =>
typeof v === 'object' ? [k, f(v)] : obj[k] = true)
f(data)
console.log(data)
If you want to toggle the values instead of setting them to true, you can do this:
const data = {"2211284396232-5":{"2211284396232-5":false,"644889430161":{"4812219518053":false,"4812219518055":false,"4812219518063":false,"4812219518064":false,"4812219518069":false,"644889430161":false}},"2211628865398-6":{"2211628865398-6":false,"729563966440":{"5229922707373":false,"729563966440":false}},"2212485574058-4":{"2212485574058-4":false,"689399023594":{"5077186698704":false,"5077186698712":false,"689399023594":false}}}
const f = obj => Object.entries(obj).forEach(([k, v]) =>
typeof v === 'object' ? [k, f(v)] : obj[k] = !obj[k])
f(data)
console.log(data)