Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
487 views
in Technique[技术] by (71.8m points)

JavaScript 【数组】转【对象】进行某些操作后转回【数组】后,得到的数组顺序和最开始的发生变化怎么解决

比如初始数组:

const arr1 = [
    {id: 1, name: 'jack'},
    {id: 3, name: 'rose'},
    {id: 2, name: 'tom'}
]

数组对象相互转化方法:

export function arrToMap(arr: any[], key: string) {
  return arr.reduce((map, item) => {
    map[item[key]] = item
    return map
  }, {})
}

export function mapToArr(map: object) {
  return Object.values(map)
}

使用:

const arrMap = arrToMap(arr1, 'id')

// 得到arrMap:
{
  "1": {
    "id": 1,
    "name": "jack"
  },
  "2": {
    "id": 2,
    "name": "tom"
  },
  "3": {
    "id": 3,
    "name": "rose"
  }
}

/*
    在得到对象后由于对象的查询是O(1)所以更快,对其进行操作后转化为数组
*/

const arr2 = mapToArr(arrMap)

// 得到arr2,顺序已经变化
[
  {
    "id": 1,
    "name": "jack"
  },
  {
    "id": 2,
    "name": "tom"
  },
  {
    "id": 3,
    "name": "rose"
  }
]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

可以用MapMap的顺序是根据插入顺序

image.png


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...