johni
johni

Reputation: 5568

Javascript object properties - create property if not exist

I'm trying to execute this piece of code in the most elegant way:

if (internalTableName in self.columnMap &&
    internalColumnName in self.columnMap[internalTableName]) {
    console.error('dupelicates');
}
else {
    try {
        self.columnMap[internalTableName][internalColumnName] = logicalColumnName;
    } catch (err) {
        self.columnMap[internalTableName] = {};
        self.columnMap[internalTableName][internalColumnName] = logicalColumnName;
    }
}

I could turn the try/catch block to:

if (internalTableName in self.columnMap &&
    internalColumnName in self.columnMap[internalTableName]) {
    console.error('dupelicates');
}
else {
    if (internalTableName in self.columnMap) {
        self.columnMap[internalTableName][internalColumnName] = logicalColumnName;
    }
    else {
        self.columnMap[internalTableName] = {};
        self.columnMap[internalTableName][internalColumnName] = logicalColumnName;

    }
}

I was wondering if Javascript offers some operators for checking nullity that could make this logic be written in a more elegant way and less IF clauses.

Thanks

Upvotes: 2

Views: 1467

Answers (3)

teh.fonsi
teh.fonsi

Reputation: 3134

Starting with JS version ES2020 you can use a nullish coalescing assignment: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_assignment

const a = { duration: 50 };

a.duration ??= 10;
console.log(a.duration);
// Expected output: 50

a.speed ??= 25;
console.log(a.speed);
// Expected output: 25

Upvotes: 1

Bergi
Bergi

Reputation: 664777

I think what you are looking for is

if (!(internalTableName in self.columnMap))
    self.columnMap[internalTableName] = {};
if (!(internalColumnName in self.columnMap[internalTableName]))
    self.columnMap[internalTableName][internalColumnName] = logicalColumnName;
else
    console.error('duplicates');

You could shorten it a bit with a helper variable and by checking for empty properties by simple falsyness:

var table = self.columnMap[internalTableName] || (self.columnMap[internalTableName] = {});
if (!table[internalColumnName])
    table[internalColumnName] = logicalColumnName;
else
    console.error('duplicates');

Upvotes: 1

epascarello
epascarello

Reputation: 207517

The common pattern is using the || operator:

self.columnMap[internalTableName] = self.columnMap[internalTableName] || {};
self.columnMap[internalTableName][internalColumnName] = logicalColumnName;

Upvotes: 3

Related Questions