'How to set value if object exists - if not intialize and set object in javascript?

I have the following result:

const mainResult = { result: 1234}

I have the following also:

const allResults = {};

I want to set allResults.results.mainResult = mainResult;

However I won't know if allResults.results exists or not. How do I create allResults.results as an object if it doesn't exist and set it to mainResults - or just set it if allResults.results.mainResults exists?

Is there a way to do this in one line?



Solution 1:[1]

Wondering why this won't work? Since we just want to write/overwrite it and not expand the object if it exists.

const mainResult = { result: 1234 };
const allResults = {};
allResults.results = { mainResult };
console.log(allResults);

Solution 2:[2]

I don't know whether there is a genuine one-line solution, but I have a forced one-line solution, which is the combination of Logical nullish assignment (??=) and Logical AND (&&) operator

const mainResult = { result: 1234 }
const allResults = {};

(allResults.results ??= {}) && (allResults.results.mainResult = mainResult)

console.log(allResults)

const mainResult = { result: 1234 }
const allResults = { results: { otherResult: 5678 } };

(allResults.results ??= {}) && (allResults.results.mainResult = mainResult)

console.log(allResults)

As @Bergi suggested, we could make it shorter

const mainResult = { result: 1234 }
const allResults = {};

(allResults.results ??= {}).mainResult = mainResult

console.log(allResults)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Parvesh Kumar
Solution 2