Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Cleanest way to set multiple object keys

Hi I was working on a text parser and I was wondering if there was a clean to rewrite the following code. Concerning the way that an object’s properties are set.

         //In the real case the parser returns varying result based on the param
         const parserResult = {'value':2,'syntaxError':false,'NaNError':false}     
         const {value,syntaxError,NaNError} = parserResult
         const param = {someProperty:'any value'} //can have any properties
         //the problem under here
         param['value'] = value
         param['syntaxError'] = syntaxError
         param['NaNError'] = NaNError
         console.log(param)

Setting three properties like that one after an other is not all that eloquent does anyone now a cleaner solution? Thanks in advance.
(complete code to test under here)

  const parseParam = param => {
         //In the real case the parser returns varying result based on the param

     const parserResult = {'value':2,'syntaxError':false,'NaNError':false}     
     const {value,syntaxError,NaNError} = parserResult
     param['value'] = value
     param['syntaxError'] = syntaxError
     param['NaNError'] = NaNError
     return param
    }
    
 const parameters = [{someProperty:'test'},{someProperty:'someValue'}]
 const parsedParameters = parameters.map(parseParam)
 console.log(parsedParameters)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You should use spread operator for this kind of stuff.

It will look like this:

const param = {...parserResult, someProperty:'any value'}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading