简体   繁体   中英

Javascript ES6 - mapping over object to produce a new array loses order of elements in object

I have a JSON object that contains a list of teams, each team has a teamCrimeCategorySum which is an object of key value pairs, where each key is a crime category and each value is the total number of crimes in that category. It is arranged alphabetically and looks like this...

alcohol:0
animal abuse:0
animal cruelty:0
animal neglect:0
assault:7
attempted murder:0
battery:1

I am looping over that to get an array of just the values like so...

teamList.map(team => {
  const newArray = Object.keys(team['teamCrimeCategorySum']).map(key => {
    return team['teamCrimeCategorySum'][key]
  })
})

This will produce an array where the original order is lost. The above object is producing this...

[18, 6, 1, 1, 7, 2, 3, ...]

I want to retain the order, such that the above object should instead produce...

[0, 0, 0, 0, 7, 0, 1, ...]

You can use below code to generate an array retaining the original order from object

  const newArray = [];
  for ( let key in tempList) {
         if(tempList.hasOwnProperty(key)) {
                newArray.push(tempList[key]);
         }
  }

Or still if you want to use Object.keys and Array.map, first sort on the keys and then call map like below

  Object.keys(tempList).sort().map(...)

@rlemon had the right idea. When I was inspecting the object in the console, it was logged in alphabetical order but the object attributes were not stored in alphabetical order. By calling .sort() , before .map() I was able to establish and then retain the alphabetical order I had intended. The function now looks like this...

  teamList.map(team => {
    const newArray = Object.keys(team['teamCrimeCategorySum'])
      .sort()
      .map(key => {
        return team['teamCrimeCategorySum'][key]
      })
    return [`${team.name}`, ...newArray, '']
  })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM