NodeJS将响应输出返回到对象数组

时间:2018-02-25 11:33:05

标签: javascript node.js

我在服务器端有一个函数从数据库中返回结果。 这是函数

    const sql = 
   `SELECT addresses
    FROM  Addresses
    WHERE JSON_EXTRACT(addresses, '$.address') LIKE ? `

  const values = ['"'+beginning+'%']

  const query = connection.query(sql, values, (error, results, fields) => {

      connection.end()
      if (error) {
        return reject(error)
      }
      resolve(results)
    })
  })
    .then((results) => {

      return {
        type: 'address',
        attributes: results

      }
    })

它的输出就像这样

    {
  "data": {
    "type": "address",
    "attributes": [
      {
        "addresses": "{\"address\": \"5 street, auburn, nsw 2144\", \"display\": \"5-7 Mary Street, AUBURN, NSW 2144\"}"
      },
      {
        "addresses": "{\"address\": \"5 street, lidcombe, nsw 2141\", \"display\": \"5 Street, LIDCOMBE, NSW 2141\"}"
      }
    ]
  }
}

我是JS的新手,我需要按照以下方式进行上述输出

{
  "data": [
    {
      "type": "address",
      "id": "5-13 aubrey street, granville, nsw 2142",
      "attributes": {
        "address": "5-13 aubrey street, granville, nsw 2142",
        "display": "5-13 Aubrey Street, GRANVILLE, NSW 2142"
      }
    },
    {
      "type": "address",
      "id": "5 street, lidcombe, nsw 2141",
      "attributes": {
        "address": "5 street, lidcombe, nsw 2141",
        "display": "5 Street, LIDCOMBE, NSW 2141"
      }
    },
    {
      "type": "address",
      "id": "5-7 mary street, auburn, nsw 2144",
      "attributes": {
        "address": "5-7 mary street, auburn, nsw 2144",
        "display": "5-7 Mary Street, AUBURN, NSW 2144"
      }
    }
    }
  ]
}

有人可以帮助我改变。然后((结果)我的功能正文来实现这一点。

在客户端,我在函数中获取结果,这就是我返回的方式

      return $http.get(`${API_URL}/addresses/?beginning=${searchTerm || ''}`)
  .then((result) => {

    // Only want to return the address string

    return result.data.data((address) => address.attributes.display)
  })

但是我得到的结果是.data.data不是函数

1 个答案:

答案 0 :(得分:1)

您可以将回报更改为

return {
    type: 'address',
    attributes: results.map(result => JSON.parse(result.addresses))
}