当值是数组时反转对象的键和值
Invert the key and value of an object while the value is an array
我有以下内容:
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 的新手。有什么有效的方法可以做到这一点?如果需要,我可以导入其他库并假设数组中的值是唯一的。谢谢
试试这个,
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);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
具有 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>');
我有以下内容:
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 的新手。有什么有效的方法可以做到这一点?如果需要,我可以导入其他库并假设数组中的值是唯一的。谢谢
试试这个,
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);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
具有 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>');