js 如何快速取反较深的json值?

比如 a.b.c.d.e = !a.b.c.d.e
有比较好的写法吗?
谢谢

阅读 2.7k
3 个回答
function negateDeep(obj) {
    if (typeof obj === 'object' && obj !== null) {
        for (let key in obj) {
            if (obj.hasOwnProperty(key)) {
                obj[key] = negateDeep(obj[key]);
            }
        }
    } else if (typeof obj === 'number') {
        obj = -obj;
    }
    return obj;
}

const jsonData = {
    a: 1,
    b: {
        c: -2,
        d: {
            e: 3,
            f: {
                g: -4
            }
        }
    }
};

const negatedData = negateDeep(jsonData);
console.log(negatedData);

没啥好方法,该走的路还是要走的

可以使用 lodash_.get_.set 方法编写一个工具函数,示例如下:

import _ from "lodash";

export function negate(object, path) {
  _.set(object, path, !_.get(object, path));
}

使用方式如下

const object = { a: { b: { c: { d: { e: true } } } } };

negate(object, "a.b.c.d.e");

也可以为 String.prototype 扩展一个 negate 方法,示例如下:

String.prototype.negate = function (object) {
  negate(object, this);
};

使用方式如下

"a.b.c.d.e".negate(object);
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题