在 JavaScript 中重新组织字典中的数据

我开始工作JavaScript并尝试一些基本的东西,所以我遇到了一个问题。

这是我的dictionary


var dic = {

    'a':  {1:'alpha', 2:'beta', 3:'delta'},

    'b' : {1:1, 2:2000, 3:50},

    'c' : {1:-9, 2:2500, 3:51},

    'd' : {1:3, 2:-1000, 3:56},

    'e' : {1:-4, 2:2005, 3:-44}, 

}

所以,我想重新排序数据,以便最终我有一个像这样的字典


var sol = {

   'alpha' : [1, -9, 3, -4],  

   'beta' : [2000, 2500, -1000, 2005],

   'delta' : [50, 51, 56, -44], 

}

a因此,我将in 中的值作为键dic,然后根据哪个索引a将相应的值b,c,d,e取出并放入数组中。


这就是我开始做的事情:


for(var i = 0; i<Object.keys(dic).length;i++){ 

    for(var j=0; j<Object.keys(dic['a']).length; j++){

      console.log(dic[i][j])

    }

}

但后来我发现我无法真正访问信息dic[i][j],我完全迷失了。


有人可以给我一些建议吗?


蓝山帝景
浏览 90回答 3
3回答

MMTTMM

我开始工作JavaScript并尝试一些基本的东西,所以我遇到了一个问题。这是我的dictionaryvar dic = {&nbsp; &nbsp; 'a':&nbsp; {1:'alpha', 2:'beta', 3:'delta'},&nbsp; &nbsp; 'b' : {1:1, 2:2000, 3:50},&nbsp; &nbsp; 'c' : {1:-9, 2:2500, 3:51},&nbsp; &nbsp; 'd' : {1:3, 2:-1000, 3:56},&nbsp; &nbsp; 'e' : {1:-4, 2:2005, 3:-44},&nbsp;}所以,我想重新排序数据,以便最终我有一个像这样的字典var sol = {&nbsp; &nbsp;'alpha' : [1, -9, 3, -4],&nbsp;&nbsp;&nbsp; &nbsp;'beta' : [2000, 2500, -1000, 2005],&nbsp; &nbsp;'delta' : [50, 51, 56, -44],&nbsp;}a因此,我将in 中的值作为键dic,然后根据哪个索引a将相应的值b,c,d,e取出并放入数组中。这就是我开始做的事情:for(var i = 0; i<Object.keys(dic).length;i++){&nbsp;&nbsp; &nbsp; for(var j=0; j<Object.keys(dic['a']).length; j++){&nbsp; &nbsp; &nbsp; console.log(dic[i][j])&nbsp; &nbsp; }}但后来我发现我无法真正访问信息dic[i][j],我完全迷失了。有人可以给我一些建议吗?

慕斯709654

你在迭代中走在正确的道路上。如果您使用 for/in 迭代对象,您可以看到您将拥有所需的所有信息:let i = 1;for (let x in dic) {&nbsp; &nbsp; &nbsp;console.log(dic[x][i])&nbsp; &nbsp; &nbsp;i++}所以第一次迭代会给你:for (let x in dic) {&nbsp; &nbsp; &nbsp;console.log(dic[x][1])}控制台显示:// alpha// 1// -9// 3

哈士奇WWW

看起来我发帖速度很慢,但这将提供您正在寻找的内容......var dic = {&nbsp; 'a': {&nbsp; &nbsp; 1: 'alpha',&nbsp; &nbsp; 2: 'beta',&nbsp; &nbsp; 3: 'delta'&nbsp; },&nbsp; 'b': {&nbsp; &nbsp; 1: 1,&nbsp; &nbsp; 2: 2000,&nbsp; &nbsp; 3: 50&nbsp; },&nbsp; 'c': {&nbsp; &nbsp; 1: -9,&nbsp; &nbsp; 2: 2500,&nbsp; &nbsp; 3: 51&nbsp; },&nbsp; 'd': {&nbsp; &nbsp; 1: 3,&nbsp; &nbsp; 2: -1000,&nbsp; &nbsp; 3: 56&nbsp; },&nbsp; 'e': {&nbsp; &nbsp; 1: -4,&nbsp; &nbsp; 2: 2005,&nbsp; &nbsp; 3: -44&nbsp; },}var dicKeys = Object.keys(dic);var sol = {};var newKeyList = Object.keys(dic.a);var newValueList = Object.values(dic.a);for (var newIndex = 0; newIndex < newKeyList.length; newIndex++) {&nbsp; var newKey = newKeyList[newIndex];&nbsp; var newValue = newValueList[newIndex];&nbsp; sol[newValue] = [];&nbsp; dicKeys.forEach(function(key) {&nbsp; &nbsp; &nbsp; if (key == 'a') {&nbsp; &nbsp; &nbsp; &nbsp; return;&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; sol[newValue].push(dic[key][newKey]);&nbsp; });}console.log(JSON.stringify(sol));
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript