反转多对多关系数组

时间:2014-06-09 07:56:10

标签: javascript

var x = {one:[1,2,3],two:[3],three:[2]}
var y = {1:['one'], 2:['three', 'one'], 3:['one', 'two']}

如何将var x转换为var y?基本上,当我想要反转时,x的格式为set->user_arraysset->user_arrays。他们得到user->set_arrays。最好是最快的解决方案和功能(地图等)

1 个答案:

答案 0 :(得分:3)

var x = {one:[1,2,3],two:[3],three:[2]}
var y = {};

for (var k in x) {
  for (var i = 0; i < x[k].length; i++) {
    y[x[k][i]] = y[x[k][i]] || [];
    y[x[k][i]].push(k);
  }
}

<强> THE WORKING DEMO.