JavaScriptES6-映射对象以生成新数组会丢失对象中元素的顺序
我有一个包含团队列表的JSON对象,每个团队都有一个JavaScriptES6-映射对象以生成新数组会丢失对象中元素的顺序,javascript,reactjs,ecmascript-6,Javascript,Reactjs,Ecmascript 6,我有一个包含团队列表的JSON对象,每个团队都有一个teamCrimeCategorySum,这是一个键值对对象,其中每个键值都是犯罪类别,每个值都是该类别中的犯罪总数。它是按字母顺序排列的,看起来像这样 alcohol:0 animal abuse:0 animal cruelty:0 animal neglect:0 assault:7 attempted murder:0 battery:1 teamList.map(team => { const newArray =
teamCrimeCategorySum
,这是一个键值对对象,其中每个键值都是犯罪类别,每个值都是该类别中的犯罪总数。它是按字母顺序排列的,看起来像这样
alcohol:0
animal abuse:0
animal cruelty:0
animal neglect:0
assault:7
attempted murder:0
battery:1
teamList.map(team => {
const newArray = Object.keys(team['teamCrimeCategorySum'])
.sort()
.map(key => {
return team['teamCrimeCategorySum'][key]
})
return [`${team.name}`, ...newArray, '']
})
我在上面循环得到一个数组,它的值如下
teamList.map(team => {
const newArray = Object.keys(team['teamCrimeCategorySum']).map(key => {
return team['teamCrimeCategorySum'][key]
})
})
这将生成一个原始顺序丢失的数组。上述对象正在生成此
[18, 6, 1, 1, 7, 2, 3, ...]
我想保留顺序,这样上面的对象应该生成
[0, 0, 0, 0, 7, 0, 1, ...]
@莱蒙的想法是对的。当我在控制台中检查对象时,它是按字母顺序记录的,但对象属性不是按字母顺序存储的。通过调用
.sort()
,在.map()
之前,我能够建立并保留我想要的字母顺序。函数现在看起来像这样
alcohol:0
animal abuse:0
animal cruelty:0
animal neglect:0
assault:7
attempted murder:0
battery:1
teamList.map(team => {
const newArray = Object.keys(team['teamCrimeCategorySum'])
.sort()
.map(key => {
return team['teamCrimeCategorySum'][key]
})
return [`${team.name}`, ...newArray, '']
})
您可以使用下面的代码生成一个数组,该数组保留对象的原始顺序
const newArray = [];
for ( let key in tempList) {
if(tempList.hasOwnProperty(key)) {
newArray.push(tempList[key]);
}
}
或者,如果仍要使用Object.keys和Array.map,请首先对键进行排序,然后像下面那样调用map
Object.keys(tempList).sort().map(...)
对象属性没有顺序。你可以调用
Object.keys(o).sort(fn).map来解决这个问题!非常感谢。我没有意识到没有顺序,因为当我把它记录到控制台时,它是按字母顺序显示的。