在Node.js中转换JSON响应

时间:2019-07-18 17:05:58

标签: arrays node.js json

我正在尝试转换json响应代码,但是我一直在获取返回的字符串数组。 标头字段取决于我查询的表,因此我无法对它们进行硬编码。

我收到一个类似json的响应:

{
  "records": [
    [
      1,
      "page one",
      300
    ],
    [
      2,
      "page 2",
      500
    ]
  ],
  "header: [
    "page_id",
    "page_name",
    "total"
  ]
}

但是我想将其转换为

{
  [
    {
      "page_id": 1,
      "page_name": "page one",
      "total": 300
    },
    {
      "page_id": 2,
      "page_name": "page 2",
      "total": 500
    }
  ]
}

我尝试创建一个Array并将其转换为json,但它仍然返回字符串数组,而不是json数组

let array = new Array;
records.forEach((record) => {
  const parts = [];
  let i = 0;
  header.forEach((title) => {
    const part = title + ': ' + record[i];
    parts.push(part);
    i++;
  });
  array.push(JSON.parse(JSON.stringify(parts)));
});
console.log(array) // Shows a string array?

我希望

{
  [
    {
      "page_id": 1,
      "page_name": "page one",
      "total": 300
    },
    {
      "page_id": 2,
      "page_name": "page 2",
      "total": 500
    }
  ]
}

但实际

[
  [ 'page_id: 1', 'page_name: page 1', 'total: 300'],
  [ 'page_id: 2', 'page_name: page 2', 'total: 500']
]

2 个答案:

答案 0 :(得分:1)

操作方式的问题是创建数组并将值推入数组,而要执行的操作是创建数组并将包含值的对象推入数组...

可以使用map(此处的文档:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map)用少量代码完成

results.records.map((arr)=> ({
  page_id: arr[0],
  page_name: arr[1],
  total: arr[2]
});

您也可以像这样解构

results.records.map(([page_id, page_name, total])=> ({
  page_id,
  page_name,
  total,
});

答案 1 :(得分:0)

/*jshint esversion: 6 */

let records = {
    "records": [
      [
        1,
        "page one",
        300
      ],
      [
        2,
        "page 2",
        500
      ]
    ],

    "header": [
      "page_id",
      "page_name",
      "total"
    ]
  }; 

  let arr1 = records.header.map(data => data + ":");
  let finalarray = new Array(10); 
   var keys = arr1; 
   var values  = records.records;  
    finalarray = [];
    values.forEach((data,index) =>{
    var objJSON = new Object({});
    for (i = 0; i < keys.length; i++) {
    objJSON[keys[i]] = data[i];
    }
    finalarray.push(objJSON);  
        });

    console.log(finalarray); 

我已将给定数据存储在records对象中,然后将标头映射为冒号“:”,在第二个循环中,我将两个数组都加入了json对象。

现在输出为:

[ { 'page_id:': 1, 'page_name:': 'page one', 'total:': 300 },
  { 'page_id:': 2, 'page_name:': 'page 2', 'total:': 500 } ]