问题
I want to toggle the Boolean value of this nested input object
var obj = { a: { b: { c: false } } };
in an efficient way so that obj
is output as:
{ a: { b: { c: true } } };
I am using:
Object.keys(obj).map(function(k, i) {
// Check if obj is Boolean else if object nest again till I find the Boolean value and toggle it.
}
回答1:
You could build a new opbject and take either an object with a recursive call or a value and return the toggled value.
const
toggle = object => Object.fromEntries(Object
.entries(object)
.map(([k, v]) => [k, v && typeof v === 'object' ? toggle(v) : !v])
);
var object = { a: { b: { c: false } } };
console.log(toggle(object));
来源:https://stackoverflow.com/questions/61890054/toggle-the-boolean-value-of-a-nested-javascript-object