需要将数组转换为逗号分隔和;nodejs中的分隔多维数组[已关闭]

cxfofazt  于 2023-04-05  发布在  Node.js
关注(0)|答案(2)|浏览(96)

已关闭,此问题需要更focused,目前不接受回答。
**想要改进此问题吗?**更新此问题,使其仅关注editing this post的一个问题。

6天前关闭。
Improve this question
下面是一个示例数组,其中有一个多维数组。我需要分开的逗号分隔和分号分隔的预期输出值

"grpdet": [
  {
    "id": 36,
    "name": "GROUP TOP A",
    "stud": [
      {
        "id": 114,
        "name": "test_stu_1"
      },
      {
        "id": 115,
        "name": "test_stu_2"
      }
    ]
  },
  {
    "id": 37,
    "name": "GROUP TOP B",
    "stud": [
      {
        "id": 116,
        "name": "test_stu_3"
      },
      {
        "id": 117,
        "name": "test_stu_4"
      }
    ]
  },
  {
    "id": 38,
    "name": "GROUP TOP C",
    "stud": [
      {
        "id": 118,
        "name": "test_stu_5"
      },
      {
        "id": 119,
        "name": "test_stu_6"
      }
    ]
  },
  {
    "id": 39,
    "name": "GROUP TOP D",
    "stud": [
      {
        "id": 120,
        "name": "test_stu_7"
      },
      {
        "id": 121,
        "name": "test_stu_8"
      }
    ]
  }
]

预期产出:

GROUP TOP A,test_stu_1,test_stu_2;GROUP TOP B,test_stu_3,test_stu_4;GROUP TOP C,test_stu_4,test_stu_5;

我尝试使用forEach,但;,出现在同一行中。

rkue9o1l

rkue9o1l1#

结合使用map()join()操作,并利用数组的默认toString()结果已经是逗号分隔字符串的事实:

const result = data.map((g) => [g.name, g.stud.map((s) => s.name)]).join(';');

完整片段:

const data = [{
  "id": 36,
  "name": "GROUP TOP A",
  "stud": [{
    "id": 114,
    "name": "test_stu_1"
  }, {
    "id": 115,
    "name": "test_stu_2"
  }]
}, {
  "id": 37,
  "name": "GROUP TOP B",
  "stud": [{
    "id": 116,
    "name": "test_stu_3"
  }, {
    "id": 117,
    "name": "test_stu_4"
  }]
}, {
  "id": 38,
  "name": "GROUP TOP C",
  "stud": [{
    "id": 118,
    "name": "test_stu_5"
  }, {
    "id": 119,
    "name": "test_stu_6"
  }]
}, {
  "id": 39,
  "name": "GROUP TOP D",
  "stud": [{
    "id": 120,
    "name": "test_stu_7"
  }, {
    "id": 121,
    "name": "test_stu_8"
  }]
}];

const result = data.map((g) => [g.name, g.stud.map((s) => s.name)]).join(';');

console.log(result);
gcuhipw9

gcuhipw92#

可以使用forEach实现所需的输出。

var grpdet = [{ id: 36, name: 'GROUP TOP A', stud: [{ id: 114, name: 'test_stu_1', }, { id: 115, name: 'test_stu_2', },], }, { id: 37, name: 'GROUP TOP B', stud: [{ id: 116, name: 'test_stu_3', }, { id: 117, name: 'test_stu_4', },], }, { id: 38, name: 'GROUP TOP C', stud: [{ id: 118, name: 'test_stu_5', }, { id: 119, name: 'test_stu_6', },], }, { id: 39, name: 'GROUP TOP D', stud: [{ id: 120, name: 'test_stu_7', }, { id: 121, name: 'test_stu_8', },], },];

var result = '';

grpdet.forEach((elem, index) => {
  result += elem.name;
  elem.stud.forEach((s, i) => {
    result += ',' + s.name;
  });
  result += ';';
});
console.log(result);

相关问题