Home > front end >  How to set value if object exists - if not intialize and set object in javascript?
How to set value if object exists - if not intialize and set object in javascript?

Time:02-10

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?

CodePudding user response:

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)

CodePudding user response:

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);
  •  Tags:  
  • Related