Return flat object from sequelize with association

后端 未结 3 1950
醉梦人生
醉梦人生 2021-01-14 08:21

I am working on converting all my queries in sequelize. The problem I have come across is that when select queries include associations (ex. one to many), the object I get

3条回答
  •  逝去的感伤
    2021-01-14 09:22

    Using raw: true a helper function can simplify the return keys. This will make sure no values are over-written and gives a way to keep some of string-based nesting (IDs for example).

    /**
      Simplify keys returned by a sequelize {raw: true} query. Makes sure no values
      are over-written and gives a way to keep some of string-based nesting (IDs for
      example).
    
      @example result.map(r => trimKeys(r))
    */
    function trimKeys(obj, deepin = ['id']) {
      const keys = Object.keys(obj)
      const ret = {}
      for (var i = 0; i < keys.length; i++) {
        const key = keys[i]
        const keyParts = key.split('.')
        let idx = 1
        let newKey = keyParts[keyParts.length - idx]
        while((ret[newKey] || deepin.find(d => newKey === d)) && idx >= 0) {
          idx++
          newKey = keyParts[keyParts.length - idx] + '.' + newKey
        }
        ret[newKey] = obj[key]
      }
      return ret
    }
    

提交回复
热议问题