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:
JavaScript
x
9
1
const obj = {a: {b: 1}};
2
3
_.set(obj, 'a.b', 2);
4
5
console.log(obj); // Great !
6
7
_.set(obj, 'a.c', 1);
8
9
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
JavaScript
1
1
1
<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.
JavaScript
1
9
1
const obj = {a: {b: 1}};
2
3
_.has(obj, 'a.b') && _.set(obj, 'a.b', 2);
4
5
console.log(obj);
6
7
_.has(obj, 'a.c') && _.set(obj, 'a.c', 2);
8
9
console.log(obj);
JavaScript
1
1
1
<script src="https://cdn.jsdelivr.net/lodash/4/lodash.min.js"></script>