0

const sendData = result => {
    result.centers.forEach(center => {
        const data = {
            center_id,
            name,
            address,
            district_name,
            state_name,
            pincode,
            fee_type,
            sessions
        } = center ;
        data.sessions = data.sessions.map(session => {
            return {
                date,
                available_capacity,
                min_age_limit,
                vaccine
            } = session ;
        })
        console.log(data) ;
    })
}

为什么上面的代码会产生以下错误?

PS:请忽略行号。

UnhandledPromiseRejectionWarning: TypeError: Assignment to constant variable.
    at /home/ubuntu/Projects/Web/CowinTracker/server/app.js:69:17
    at Array.map (<anonymous>)
    at /home/ubuntu/Projects/Web/CowinTracker/server/app.js:67:39
    at Array.forEach (<anonymous>)
    at sendData (/home/ubuntu/Projects/Web/CowinTracker/server/app.js:56:20)

我尝试更改const datalet data并发生相同的错误。

4

1 回答 1

1

您不能在 return 语句中进行解构。

您需要解构会话参数,或引用会话对象并将属性分配给新对象。

const data = {
  centers: [
    {
      center_id: 1,
      name: 'One',
      address: '1 one street',
      district_name: 'one',
      state_name: 'one',
      pincode: '1111',
      fee_type: 1,
      sessions: [
        {
          date: new Date(),
          available_capacity: 1,
          min_age_limit: 1,
          vaccine: "its gene therapy"
        }
      ]
    }
  ]
}


const sendData = result => {
    result.centers.forEach(center => {
        const data = {
            center_id,
            name,
            address,
            district_name,
            state_name,
            pincode,
            fee_type,
            sessions
        } = center ;
        data.sessions = data.sessions.map(session => {
            return {
                date: session.date,
                available_capacity: session.available_capacity,
                min_age_limit: session.min_age_limit,
                vaccine: session.vaccine
            } ;
        })
        console.log(data) ;
    })
}

sendData(data)

如果你想解构会话参数,你可以做这样的事情。

data.sessions = data.sessions.map((( 
  date, 
  available_capacity,
  min_age_limit,
  vaccine,
}) => ({
    date,
    available_capacity,
    min_age_limit,
    vaccine,
}) 

})

如果您只是克隆对象,则可以执行以下操作。

data.sessions = data.sessions.map(session => ({
  ...session
}))
于 2021-05-08T17:23:47.183 回答