Home > Back-end >  One line to check to see if an property is an object and then fill with value
One line to check to see if an property is an object and then fill with value

Time:08-31

I currently have the following code which checks to see if a property is nullish, if it is I create an empty object, and then "push" a value into that object on the next line.

const a = {};

a.b ??= {};
a.b.c= 1;

console.log(a)

I am curious if JS supports this operation with a single line of code.

Note that it is important that IF b already is an object with data that that data is preserved when a.b.c is set.

CodePudding user response:

I suggest you keep your code as two lines for readability, but you could just stuff the first line into an if statement. However do keep in mind that if a.b is falsey (0, "", false), then this hack will fail.

const a = {};

// if nullish, {} is truthy, otherwise, any object is still truthy
if (a.b ??= {}) a.b.c = 1;

// make some changes
a.b.d = 2;
a.b.c = 3;

// doesn't "reset" the property if it does exist
if (a.b ??= {}) a.b.c = 1;

console.log(a);

CodePudding user response:

Turns out I wanted Object.assign() with the null assignment operator inside the first argument.

const a = {b: {z: 2}};
Object.assign(a.b ??= {}, {c: 1})
console.log(a)

const a2 = {};
Object.assign(a2.b ??= {}, {c: 1})
console.log(a2)

  • Related