如何在JavaScript中将字符串中的某些部分作为组?

时间:2019-03-03 23:31:50

标签: javascript node.js regex

我想使用正则表达式将字符串中的某些部分分组。我尝试了许多解决方案,但是它们没有用。

我的整个字符串的一部分:

...

{"name":"AE102-Fundamentals of Automotive Engineering","short":"AE102","color":"#00C0FF","picture":"",
"timeoff":[
[
["1"]]],"id":"-696","picture_url":""},

{"name":"AE202 lab-Fuels and Combustion lab","short":"AE202 lab","color":"#FF5050","picture":"",
"timeoff":[
[
["1"]]],"id":"-697","picture_url":""},

{"name":"AE202-Fuels and Combustion","short":"AE202","color":"#CCFFFF","picture":"",
"timeoff":[
[
["1"]]],"id":"-698","picture_url":""},

...

输出应类似于:

[
   {"name":"...","short":"...","id":"..."},
   {"name":"...","short":"...","id":"..."},
   ....
]

此外,该平台是节点js。

1 个答案:

答案 0 :(得分:3)

请勿为此使用正则表达式-而是使用JSON.parse解析JSON,并使用.map从每一行中提取所需的属性:

function parse() {
  const obj = JSON.parse(input);
  const newRows = obj.map(({ name, short, id }) => ({ name, short, id }));
  console.log(newRows);
}

const input = `[{
    "name": "AE102-Fundamentals of Automotive Engineering",
    "short": "AE102",
    "color": "#00C0FF",
    "picture": "",
    "timeoff": [
      [
        ["1"]
      ]
    ],
    "id": "-696",
    "picture_url": ""
  },

  {
    "name": "AE202 lab-Fuels and Combustion lab",
    "short": "AE202 lab",
    "color": "#FF5050",
    "picture": "",
    "timeoff": [
      [
        ["1"]
      ]
    ],
    "id": "-697",
    "picture_url": ""
  },

  {
    "name": "AE202-Fuels and Combustion",
    "short": "AE202",
    "color": "#CCFFFF",
    "picture": "",
    "timeoff": [
      [
        ["1"]
      ]
    ],
    "id": "-698",
    "picture_url": ""
  }
]`;
parse();