拆分字符串以获取带数组的对象

时间:2016-01-29 11:25:51

标签: javascript arrays

我需要拆分一个看起来像这样的字符串:

75,"first, result
another line
third, or more"
77,"just one line"

我需要得到的是一个带有两个字段的对象,第二个字段带有数组:

{ 
    id: 75,
    lines: 
        [
            'first, result',
            'another line',
            'third, or more'
        ]
},
{ 
    id: 77,
    lines: 
        [
            'just one line'
        ]
}

我的问题是,有换行符和逗号。因此str.split(",");无效。

4 个答案:

答案 0 :(得分:3)

这是一个带正则表达式的简单解决方案:

var arr, objs = [], r = /(\d+),\s*"([^\"]+)"/gm;
while (arr=r.exec(str)){
  objs.push({id:+arr[1], lines:arr[2].split('\n')})
}

见下面的演示:

var str = '75,"first, result\nanother line\nthird, or more"\n77,"just one line"';
var arr, objs = [], r = /(\d+),"(\s*[^\"]+)"/gm;
while (arr=r.exec(str)){
  objs.push({id:+arr[1], lines:arr[2].split('\n')})
}
document.body.style.whiteSpace = 'pre';
document.body.textContent = JSON.stringify(objs,null,'\t');

答案 1 :(得分:0)

var output = [];

var lines = str.split( "\n" ); //str is the input string, split it by line separator
lines.forEach( function(value){

  var items = value.split(","); //split each line by comma
  if (isNaN(items[0])) //if first number is not number then push it last array
  {
      output[output.length - 1 ].lines.push( value );
  }
  else //else push a new item
  {
      output.push({
         id : items[0],
         lines : [items[1]]
      });
  }
} );       
console.log(output);

答案 2 :(得分:0)

str.split('\"')适用于您的情况。

答案 3 :(得分:0)

这应该这样做:

const text = `75,"first, result
another line
third, or more"
77,"just one line"`;
let result = [];
const expected = [
  { 
    id: 75,
    lines: 
    [
      'first, result',
      'another line',
      'third, or more'
    ]
  },
  { 
    id: 77,
    lines: 
    [
      'just one line'
    ]
  }
];

var actual = text
            .replace(/\"/g, '')
            .split("\n")
            .reduce((accum, line, index) => {
              var idMatches = line.match(/^(\d+)(.*)$/);
              if(idMatches){
                accum.push({
                  id: parseInt(idMatches[1], 10),
                  lines: [idMatches[2].replace(/^,/, '')]
                });
              }else{
                accum[accum.length - 1].lines.push(line)
              }
              return accum;
            }, []);
console.log('Expected:', expected);         
console.log('Actual:', actual);

和jsbin链接:https://jsbin.com/luruhukiti/1/edit?js,console