我有以下内容:
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的新手。有没有有效的方法来做到这一点?如果需要,我可以导入其他库,并假设数组中的值是唯一的。感谢。
答案 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);
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;
答案 1 :(得分:0)
具有forEach
和arrow
功能(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>');