Tuan Ryan
Tuan Ryan

Reputation: 3

Javascript split multi line string to object

I need help. I have string:

let str = `123.123.123.123|admin|admin|Russian Federation (RU)||SPEED: 5
123.123.123.13|user|user|Russian Federation (RU)||SPEED: 5
123.123.121.3|fpt|user|Russian Federation (RU)||SPEED: 5`

I want:

ssh_config = [ {
  host: '123.123.123.123',
  port: 22,
  username: 'admin',
  password: 'admin'
},
{
   host: '123.123.123.13',
   port: 22,
   username: 'user',
   password: 'user'
},
{
   host: '123.123.121.3',
   port: 22,
   username: 'fpt',
   password: 'user'
}]

please help. Thanks so much. I don't known code it with javascript.

Upvotes: 0

Views: 94

Answers (2)

user4639281
user4639281

Reputation:

Split the string by the new lines, map the result to a split of the elements by the | symbol reduced to an Object containing the expected fields.

let str = `123.123.123.123|admin|admin|Russian Federation (RU)||SPEED: 5
123.123.123.13|user|user|Russian Federation (RU)||SPEED: 5
123.123.121.3|fpt|user|Russian Federation (RU)||SPEED: 5`;
// [p]roperties, [t]emplate, [f]unction, [s]tring, [l]ine, [a]ccumulator, [e]lement, [i]ndex
const p = ['host', 'username', 'password'], t = () => ({ port: 22 });
const f = s => s.split('\n').map(l => l.split('|').reduce((a, e, i) => (i in p && (a[p[i]] = e), a), t()));

console.log(f(str))

Upvotes: 2

smarber
smarber

Reputation: 5084

let str = `123.123.123.123|admin|admin|Russian Federation (RU)|22|SPEED: 5
123.123.123.13|user|user|Russian Federation (RU)|22|SPEED: 5
123.123.121.3|fpt|user|Russian Federation (RU)|22|SPEED: 5`;
const HOST = 0,
      PORT = 4,
      USERNAME = 1,
      PASSWORD = 2;

const FIELD_SEP = '|';



var ssh_config = (function strtoObject(string) {
    var lines = string.split(/\r\n|\n/),
        result = [];
        
        
    for (var i = 0, c = lines.length; i < c; i++) {
        var fields = lines[i].split(FIELD_SEP),
            localObj = {
              host: fields[HOST],
              port: fields[PORT],
              username: fields[USERNAME],
              password: fields[PASSWORD],
            };
            
            result.push(localObj);
    }
    
    return result;
})(str);

console.info(ssh_config);

Upvotes: 0

Related Questions