Skip to content
Advertisement

Lodash _.set only if object exists

I am looking to set inner properties of an object only if they already exist. Lodash _.set will create the whole hierarchy if it does not exist.

Is there an easy way to do this ? (Without and if statement ?)

Snippet below:

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>

Advertisement

Answer

The answer from Kalaiselvan A below put me on the way but this is not quite what I was looking for.

Using the same idea but improving the ternary gives me the following solution which I am happy with.

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>
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement