在值为数组时反转对象的键和值

时间:2015-02-23 09:28:12

标签: javascript jquery node.js underscore.js

我有以下内容:

var object = {
    a: ["A1"],
    b: ["B1", "B2"],
    c: ["C1", "C2", "C3", "C4"]
};

我想将上述内容转换为:

var result = {
    A1: "a",
    B1: "b",
    B2: "b",
    C1: "c",
    C2: "c",
    C3: "c",
    C4: "c"
};

我是Javascript的新手。有没有有效的方法来做到这一点?如果需要,我可以导入其他库,并假设数组中的值是唯一的。感谢。

2 个答案:

答案 0 :(得分:2)

试试这个,

var object = {
  a: ["A1"],
  b: ["B1", "B2"],
  c: ["C1", "C2", "C3", "C4"]
};
var keys = Object.keys(object);
var obj = {};
for(var j=0,l=keys.length;j<l;j++){
  for (var i = 0; i < object[keys[j]].length; i++) {
    obj[object[keys[j]][i]] = keys[j];
  }
}
console.log(obj);

&#13;
&#13;
var object = {
  a: ["A1"],
  b: ["B1", "B2"],
  c: ["C1", "C2", "C3", "C4"]
};
var keys = Object.keys(object);
var obj = {};

for(var j=0,l=keys.length;j<l;j++){
  for (var i = 0; i < object[keys[j]].length; i++) {
    obj[object[keys[j]][i]] = keys[j];
  }
}
console.log(obj);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

具有forEacharrow功能(ES6标准)的解决方案

var object = { a: ["A1"], b: ["B1", "B2"], c: ["C1", "C2", "C3", "C4"] };

var result = {};

Object.keys(object).forEach(k =>
    object[k].forEach(a => result[a] = k));

document.write('<pre>' + JSON.stringify(result, 0, 2) + '</pre>');