JS 对象属性名排序 - Fish-Blog - 博客园

问题,对象属性名排序,如:

var data = { A:[], D:[], B:{} }

调整为=>

var data = { A:[], B:[], D:{} }

方法一:

for,in,把fieldname保存到一个数组中,sort,然后根据sort顺序把原对象的值保存到新对象中

var arr=[];
for(var key in data){
    arr.push(key)
}
arr = arr.sort()
var newData={}
for(var i in arr){
    var itemKey = arr[i]
    newData[itemKey] = data[itemKey]
}

方法二-ES6:

var newData = {};
Object.keys(data).sort().map(key => {
  newData[key]=s[key]
})

我的代码是这样的

// 引入汉字转拼音插件文件
  import vPinyin from '../../utils/vue-py'

  export default {
    name   : "selectCity",
    data() {
      return {
        optionsProvince: [],
        optionsCity    : [],
        optionsTown    : [],
        cityForm       : {
          province: '',// string 省 否
          city    : '',// string 市 否
          town    : '',// string 区 否

        },

        hotCity    : [
          {name: "北京", code: "110000"},
          {name: "上海", code: "110000"},
          {name: "广州", code: "110000"},
          {name: "深圳", code: "110000"},
          {name: "天津", code: "110000"},
          {name: "西安", code: "110000"},
          {name: "重庆", code: "110000"},
          {name: "杭州", code: "110000"},
          {name: "南京", code: "110000"},
          {name: "武汉", code: "110000"},
          {name: "成都", code: "110000"},
        ],
        historyCity: [
          {name: "北京", code: "110000"},
        ],
        groupByCity: {}
      }
    },
    methods: {
      // TODO change 事件
      selectProvinceChange(value) {

        console.log('selectProvinceChange,', value)
        console.log('表单数据:', JSON.stringify(this.cityForm))

        let curProvinceIndex = this.optionsProvince.findIndex(item => item.code === value)

        console.log(curProvinceIndex)

        this.optionsCity = this.optionsProvince[curProvinceIndex].citys

        console.log(this.optionsCity)

        this.cityForm.city = ''
        this.cityForm.town = ''

      },
      selectCityChange(value) {
        console.log('selectCityChange,', value)
        console.log('表单数据:', JSON.stringify(this.cityForm))

        let curCityIndex = this.optionsCity.findIndex(item => item.code === value)

        console.log(curCityIndex)

        this.optionsTown = this.optionsCity[curCityIndex].towns

        console.log(this.optionsCity)

        this.cityForm.town = ''

      },
      selectTownChange(value) {
        console.log('selectTownChange,', value)
        console.log('表单数据:', JSON.stringify(this.cityForm))

      },

      // TODO 5.获取城市代码 getCityCode
      handleGetCityCode() {

        const params = {

          // brand_id: 8//localStorage.getItem('brand_id')
        }

        console.log('params', params)

        this.$store.dispatch('getCityCode', params).then((res) => {

          console.log(res)
          if (res && res.data && res.status === 200) {
            console.log(res.data)

            this.optionsProvince = res.data.list

            // 修正 拼音
            this.optionsProvince.forEach((_province, index) => {

              // 调用汉字转拼音方法
              this.$set(_province, 'pinyin', vPinyin.chineseToPinYin(_province.name))

              _province.citys.forEach((_city, index) => {

                var pinyin  = vPinyin.chineseToPinYin(_province.name)
                var pinyin_ = pinyin.substr(0, 1)

                // 调用汉字转拼音方法
                this.$set(_city, 'pinyin', pinyin)

                console.log('groupByCity :', pinyin_, '是否存在:', this.groupByCity.hasOwnProperty(pinyin_))

                if (this.groupByCity.hasOwnProperty(pinyin_) == false) {

                  var _cityGroup = []
                  _cityGroup.push(_city)
                  this.$set(this.groupByCity, pinyin_, _cityGroup)
                  // this.groupByCity[pinyin_] = _cityGroup
                  console.log('初始化', this.groupByCity[pinyin_])


                } else {
                  console.log(this.groupByCity[pinyin_])
                  this.groupByCity[pinyin_].push(_city)
                }

                // Array.hasOwnProperty()

              })
            })

            // console.log(JSON.stringify(this.optionsProvince))
            // console.log('groupByCity',this.groupByCity)

            // this.groupByCity = _.sortBy(this.groupByCity)


            var newData = {};
            Object.keys(this.groupByCity).sort().map(key => {
              newData[key] = this.groupByCity[key]
            })


            this.groupByCity.forEach((group, index) => {
              console.log(group)
            })
            // console.log(this.groupByCity.keys())

            // 修正 select 下拉数据
            console.log('修正 select 下拉数据 start =======================================>')

            // let curProvinceIndex = this.optionsProvince.findIndex(item => item.name === this.cityForm.province)
            // console.log('查找 省 name = ', this.cityForm.province, curProvinceIndex)
            // if (curProvinceIndex >= 0) {
            //   this.optionsCity = this.optionsProvince[curProvinceIndex].citys
            // }

            // let curCityIndex = this.optionsCity.findIndex(item => item.name === this.cityForm.city)
            // console.log('查找 市 name = ', this.cityForm.city, curCityIndex)
            // if (curCityIndex >= 0) {
            //   this.optionsTown = this.optionsCity[curCityIndex].towns
            // }

            console.log('修正 select 下拉数据  end  =======================================>')
          }

        })
      },
    },
    created() {

      this.handleGetCityCode()
    },
  }

Original url: Access
Created at: 2020-03-09 09:18:03
Category: default
Tags: none

请先后发表评论
  • 最新评论
  • 总共0条评论