3

Simple question: writing code in javascript, I find myself write the same lines of code over and over:

if (!obj.field) obj.field={};
obj.field.inner_field='val';

In order to protect myself from cases where obj.field is not defined. Is there a more elegant way to do it?

Thanks!

orshachar
  • 4,837
  • 14
  • 45
  • 68
  • How about using `Object.assign`? – Pardeep Dhingra Aug 10 '16 at 10:55
  • Possible duplicate of [Set default value of javascript object attributes](http://stackoverflow.com/questions/6600868/set-default-value-of-javascript-object-attributes) – Craicerjack Aug 10 '16 at 10:56
  • Possible solution: `obj.field = Object.assign({}, {inner_field: "val"})` –  Aug 10 '16 at 10:59
  • Possible duplicate of [Automatically create object if undefined](http://stackoverflow.com/questions/17643965/automatically-create-object-if-undefined) – vesse Aug 10 '16 at 11:00

1 Answers1

0

You can use the in operator.

var obj = {};
    
if (!('field' in obj)) {
    obj.field = {};
}
obj.field.inner_field = 'val';
console.log(obj);

Or you can use Object.assign() (notes: this overwrites possibly existing fields).

var obj = {};
obj.field = Object.assign({}, {inner_field: 'val'})
console.log(obj);

Alternatively you can use:

var obj  = {};
obj.field  = obj.field  || {};
obj.field.inner_field  = 'val';
console.log(obj);

Documentation: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/assign

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/in

GibboK
  • 71,848
  • 143
  • 435
  • 658
  • 1
    `obj.field = Object.assign({}, {inner_field: 'val'})` overwrites possibly existing `field`. OP uses `if` obviously because he does not want to overwrite the whole object, just a single key. Performance aside you could do `obj.field = Object.assign(obj.field || {}, {inner_field : 'val'});` to keep other keys. – vesse Aug 10 '16 at 11:13
  • @vesse thanks for your comment I made an edit to my answer :) – GibboK Aug 10 '16 at 11:18
  • My variant is `obj.field = Object.assign({}, obj.field, {inner_field: 'val'})`. Your first and third variants have a little defect if `obj.field` is `number` or `string`. – Aikon Mogwai Aug 10 '16 at 11:18