1

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);
2
  • Can you edit your code to include merchantIdList because your code currently returns Uncaught ReferenceError: merchantIdList is not defined Commented Jan 4, 2022 at 19:41
  • The code is building a comma separated string of ref-id and ref-value fields. Can't say more without seeing merchantIdList. Commented Jan 4, 2022 at 19:44

1 Answer 1

1

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);

Sign up to request clarification or add additional context in comments.

1 Comment

This is a really old piece of code. Thank you tons. Understood everything.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.