Toggle the Boolean value of a nested JavaScript object [closed]

做~自己de王妃 提交于 2020-05-24 05:11:59

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!