0

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

  • What is `['clientMap'][0]['legalEntityNumber']`? This evaluates to `'clientMap'.legalEntityNumber`, which in turn is `undefined`. – trincot Jun 30 '22 at 16:31
  • https://stackoverflow.com/questions/8051975/access-object-child-properties-using-a-dot-notation-string – epascarello Jun 30 '22 at 16:32

2 Answers2

0

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("")
Itay Wolfish
  • 507
  • 3
  • 9
  • thanks Itay! it works, however I achieve the result using _.set function of lodash library _.set(dataCopy, ['clientMap', 0, 'legalEntityNumber'], value); – Dinesh Kumar Jun 30 '22 at 16:43
0

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}]`, '');
Aaron Turkel
  • 144
  • 1
  • 11