In React / ES6, is there a more concise way to write a triplet referencing an attribute?
In my code right now, I have a code like this: starterValue={ elementToEdit ? elementToEdit.size : null }
I cannot do elementToEdit.size || null
or something like that due to elementToEdit
undefined, it clearly cannot get its attribute.
Is there a more concise way to write this, or should I just work it out? Thanks to
source to share
You can use destruction assignment :
var obj = {
size: 10
};
var {size} = obj;
console.log(size);
obj = null;
var {size} = obj || {}; // Note here we do not use null, but an empty object
console.log(size);
source to share
A short way to do this in JavaScript is to use a function get
from Lodash that gives undefined
in case of an object null
or undefined
instead of throwing an error:
var el1 = { size: 2 };
var el2 = null;
console.log(_.get(el1, 'size'));
console.log(_.get(el2, 'size'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
If you want to have null
instead undefined
, you can use the third parameter for the default:
var el1 = { size: 2 };
var el2 = null;
console.log(_.get(el1, 'size', null));
console.log(_.get(el2, 'size', null));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
source to share
One option is to add a helper method and reuse it:
const getVal = (obj, key) => obj ? obj[key] : null
and then you can do starterValue = getVal(elementToEdit, 'size');
There are other tricks you can use with ES2015 proxy , but this requires an external object.
So if you were able to refactor your code instead of elementToEdit
as an external variable, but instead of something like const allElements = { elementToEdit };
Then you could use a proxy to set the default value for the elementToEdit.size to null if not.
source to share
If elementToEdit
already named but possibly undefined, you can simply do:
(elementToEdit && elementToEdit.size) || null
If it is unnamed and has no idea if it was named / defined afterwards, you will need to do the type checking in the same order:
(typeof elementToEdit === 'object' && elementToEdit.size) || null
source to share