I have been using some code to check the value for a input field which is present at index:1 of an array. It is as below
const inputValue=journeyData && journeyData.birthdate && journeyData.birthdate[0]
? journeyData.birthdate[0]
: null,
Is there a lodash replacement for the same thing which makes it shorted to write ?
You can use _.get()
which allows specifying a path and also a fallback. If the path cannot be reached on the object, you get the default value:
function test(journeyData) {
const inputValue = _.get(journeyData, "birthdate[0]", null);
return inputValue;
}
console.log( test() ); // null
console.log( test({}) ); // null
console.log( test({ birthdate: [] }) ); // null
console.log( test({ birthdate: [42] }) ); // 42
<script src="https://cdn.jsdelivr.net/npm/[email protected]/lodash.min.js"></script>