简体   繁体   中英

Replace String in Bidimensional array

I scrape a webpage that it has a table. I returned the array like this:

[
  [
    'Veículo',
    'Entrega\nSem/Com oco\nQtde',
    'Entrega\nSem/Com oco\nKg',
    'Com oco Kg\n%'
  ],
  [
    'AAA3B43',
    '0 / 29',
    '0 / 1.712',
    '100\n100\n100\n '
  ],
  [
    'BBB8922',
    '0 / 22',
    '0 / 1.170',
    '100\n100\n100\n '
  ]
];

My array is bigger than this and it have a lot of columns, with empty fields. I posted just the necessary.

Then, I would like to return the same data but replacing \n by | to save in a text file and proccess this after that.

I tried the code below but this not working.


var oldArray = [
  [
    'Veículo',
    'Entrega\nSem/Com oco\nQtde',
    'Entrega\nSem/Com oco\nKg',
    'Com oco Kg\n%'
  ],
  [
    'AAA3B43',
    '0 / 29',
    '0 / 1.712',
    '100\n100\n100\n '
  ],
  [
    'BBB8922',
    '0 / 22',
    '0 / 1.170',
    '100\n100\n100\n '
  ]
];

var newArray = new Array;

oldArray.forEach((lines, index) => {
  lines.forEach((childLines, childIndex) => {
    newArray.push(lines.map(function(item){
      return item.replace(/\r?\n|\r/g,'|');
    }));
  });
  
});

console.log(newArray);

May anyone help me?

You are already looping over the strings in your inner array with the inner .forEach() loop, so there is no need too perform another iteration over these with .map() , instead, you can update your .push() method to just push the update string value:

newArray.push(childLines.replace(/\r?\n|\r/g,'|'));

Your callbacks also don't need to accept index arguments if you never use them, passing just the element will work also:

 var oldArray = [[ 'Veículo', 'Entrega\nSem/Com oco\nQtde', 'Entrega\nSem/Com oco\nKg', 'Com oco Kg\n%' ], [ 'BTT3B43', '0 / 29', '0 / 1.712', '100\n100\n100\n ' ], [ 'EKV8922', '0 / 22', '0 / 1.170', '100\n100\n100\n ' ]]; var newArray = []; oldArray.forEach(lines => { lines.forEach(childLines => { newArray.push(childLines.replace(/\r?\n|\r/g,'|')); }); }); console.log(newArray);

Or, if you prefer, you can use .map() , which might be more suitable since you want to create a new array of mapped values:

 const oldArray = [[ 'Veículo', 'Entrega\nSem/Com oco\nQtde', 'Entrega\nSem/Com oco\nKg', 'Com oco Kg\n%' ], [ 'BTT3B43', '0 / 29', '0 / 1.712', '100\n100\n100\n ' ], [ 'EKV8922', '0 / 22', '0 / 1.170', '100\n100\n100\n ' ]]; const newArray = oldArray.map( lines => lines.map(childLines => childLines.replace(/\r?\n|\r/g,'|')) ); console.log(newArray);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM