Javascript将多行字符串拆分为对象

时间:2017-03-14 16:32:33

标签: javascript arrays string object

我需要帮助。 我有字符串:

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`

我想:

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'
}]

请帮忙。非常感谢。 我不知道使用javascript编写代码。

2 个答案:

答案 0 :(得分:2)

按新行分割字符串,将结果映射到元素的分割,|符号缩小为包含预期字段的对象。

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

答案 1 :(得分:0)

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