Home > OS >  Convert comma seperated values into object specified method
Convert comma seperated values into object specified method

Time:07-01

Hi I am trying to achieve following behaviors with javascript

let fieldsArray = ['clientMap', 0, 'legalEntityNumber']

somehow I want to get convert above data into following way

['clientMap'][0]['legalEntityNumber']

I tried with fieldsArray.join('[]') but its not working as expected. please help. Thanks

CodePudding user response:

This will do assuming you intended to convert the items to array of arrays (Type: (string|number)[][])

let fieldsArrayArray = ['clientMap', 0, 'legalEntityNumber'].map(item=>[item])

Basically mapping each element of the array outputting single item array.

If the output should be string then for some reason (Type: string)

let fieldsArrayStringArrays = ['clientMap', 0, 'legalEntityNumber'].map(item=>`[${item}]`).join("")

CodePudding user response:

If im understanding you correctly (and you want a string i.e. "[clientMap][0][legalEntityNumber]") this would be how to do that...

let fieldsArrayString = ['clientMap', 0, 'legalEntityNumber'].map(item=>`[${item}]`).join('');

or

let fieldsArrayString = ['clientMap', 0, 'legalEntityNumber'].reduce((acc, cur) => `${acc}[${cur}]`, '');
  • Related