仅当对象存在时,Lodash _.set

时间:2017-12-07 02:53:57

标签: javascript lodash

我希望只有在对象已存在的情况下才设置它们的内部属性。如果Lodash _.set不存在,它将创建整个层次结构。

有一种简单的方法吗? (没有和if语句?)

以下代码段:

const obj = {a: {b: 1}};

_.set(obj, 'a.b', 2);

console.log(obj); // Great !

_.set(obj, 'a.c', 1);

console.log(obj); // Great but not what I want. I would like c not to be set because it does not exist in the first place
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

3 个答案:

答案 0 :(得分:3)

你可以通过这种方式尝试

const obj = {a: {b: 1}};

_.set(obj, 'a.b', 2);

console.log(obj); // Great !
_.has(obj,'a.c')==true?_.set(obj, 'a.c', 1):""

console.log(obj); // Great but not what I want. I would like c not to be set because it does not exist in the first place
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

答案 1 :(得分:1)

您可以查看Object.seal

但是,你会想要深深地&#34;密封物体:

&#13;
&#13;
const sealDeep = obj => {
    const sealProps = o => {
        Object.values(o).forEach(value => {
            if (typeof value === 'object') {
                sealProps(value);
                Object.seal(value);
            }
        });
    };
    sealProps(obj);
    Object.seal(obj);
};

var x = {
    hello: {
        world: {
            foo: 1,
            bar: 2
        },
        bat: '3'
    },
    foo2: 4
};
sealDeep(x);
console.log(JSON.stringify(x));
x.newthing = 999;
x.hello.newthing = 999;
x.hello.world.newthing = 999;
x.hello.world.foo = 999;
console.log(JSON.stringify(x));
&#13;
&#13;
&#13;

答案 2 :(得分:1)

以下Kalaiselvan A的回答让我走上了路,但这并不是我想要的。

使用相同的想法,但改进三元为我提供了以下解决方案,我很满意。

const obj = {a: {b: 1}};

_.has(obj, 'a.b') && _.set(obj, 'a.b', 2);

console.log(obj);

_.has(obj, 'a.c') && _.set(obj, 'a.c', 2);

console.log(obj);
<script src="https://cdn.jsdelivr.net/lodash/4/lodash.min.js"></script>