Home > Back-end >  Parsing 2D Array In Javascript
Parsing 2D Array In Javascript

Time:01-05

Can someone please help and give an example of what is happening here.

I am fairly new to Javascript and IT field and unable to understand what is happening. Please help.

let merchantPanToString = '';
for (let i = 0; i < merchantIdList.length; i  ) {
  merchantPanToString = merchantPanToString   merchantIdList[i]['ref-id']   ','   merchantIdList[i]['ref-value'];
  if (i != merchantIdList.length - 1) {
    merchantPanToString = merchantPanToString   ',';
  }
}

console.log(merchantPanToString);

CodePudding user response:

It is a very verbose way to make a comma delimited string out of something iterable. I do not think it is a 2D array, more likely an object array but you need to post the array to show me

For one merchantPanToString = merchantPanToString

can be written

merchantPanToString =

Note we need to access the values using [] bracket notation because of the - in the item keys

I show a map in the second example

const merchantIdList = [
{ 'ref-id' : 'AId', 'ref-value' : 'AVal' },
{ 'ref-id' : 'BId', 'ref-value' : 'BVal' },
{ 'ref-id' : 'CId', 'ref-value' : 'CVal' },
{ 'ref-id' : 'DId', 'ref-value' : 'DVal' }
];

let merchantPanToString = '';
for (let i = 0; i < merchantIdList.length; i  ) { // loop from 0 to but not including the length of the array
  merchantPanToString = merchantPanToString   // concatenate merchantPanToString to previous merchantPanToString
  merchantIdList[i]['ref-id']   ','   merchantIdList[i]['ref-value']; // plus the two values
  if (i != merchantIdList.length - 1) { // ugly way to NOT add a comma at the end
    merchantPanToString = merchantPanToString   ',';
  }
}
console.log(merchantPanToString);

// modern way - no let here because I reuse the variable from above so you do need a let or const in your code:
// const merchantPanToString = merchantIdList ...
merchantPanToString = merchantIdList
  .map(item => `${item['ref-id']},${item['ref-value']}`) // using template literals to join the values
  .join(','); // join the comma pairs with comma
console.log(merchantPanToString);

  •  Tags:  
  • Related