Lodash replacement for a JS check operation to set value

Viewed 18

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 ?

2 Answers

Use native optional chaining. No need for lodash.

const journeyData = { birthdate: [new Date()] };

const inputValue = journeyData?.birthdate?.[0] ?? null;
const inputValue2 = journeyData?.birthdate?.[2] ?? null;

console.log(inputValue);
console.log(inputValue2);

Additional documentation

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/lodash@4.17.21/lodash.min.js"></script>

Related