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

+3


source to share


5 answers


Assuming there elementToEdit

is null

when it is not, you can do

starterValue={ elementToEdit && elementToEdit.size }

      



If this undefined

or some other value is fake, that value will be passed instead, but that is probably fine in your usecase as well.

+1


source


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);
      

Run codeHide result


+1


source


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>
      

Run codeHide result


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>
      

Run codeHide result


0


source


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.

0


source


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

0


source







All Articles