javascript - 我需要反转对象的格式
问题描述
我在下面有这个对象,我需要使用函数transform(oldScoreKey)
来重新格式化对象,所以字母是键,数字是值。
我知道如何使用for
循环内的for...in
循环迭代对象内的每个字母,但我不明白我应该如何让函数对对象本身进行实际的重新格式化。
这是我的代码:
//here is the oldScoreKey
const oldScoreKey = {
1: ['A', 'E', 'I', 'O', 'U', 'L', 'N', 'R', 'S', 'T'],
2: ['D', 'G'],
3: ['B', 'C', 'M', 'P'],
4: ['F', 'H', 'V', 'W', 'Y'],
5: ['K'],
8: ['J', 'X'],
10: ['Q', 'Z']
};
//here is the basic format of what I have thus far,
//as far as the layout of the transform function
function transform(obj) {
const newScorekey = {};
for (var key in oldScoreKey) {
for(let i = 0; i < oldScoreKey[key].length; i++) {
return oldScoreKey[key][i].toLowerCase();
}
} return newScorekey;
}
transform(oldScoreKey);
//the final output should be like this,
//but it doesn't need to be in this exact order,
//only such that the point values match those in oldScoreKey
const newScorekey = {
a: 1,
b: 3,
c: 3,
d: 2,
e: 1,
f: 4,
g: 2,
h: 4,
i: 1,
j: 8,
k: 5,
l: 1,
m: 3,
n: 1,
o: 1,
p: 3,
q: 10,
r: 1,
s: 1,
t: 1,
u: 1,
v: 4,
w: 4,
x: 8,
y: 4,
z: 10
}
解决方案
你不应该在循环中返回,否则它只会返回一个键而不是完成执行,你可以填充newScoreKey
对象,并在循环完成时返回:
const oldScoreKey = {
1: ['A', 'E', 'I', 'O', 'U', 'L', 'N', 'R', 'S', 'T'],
2: ['D', 'G'],
3: ['B', 'C', 'M', 'P'],
4: ['F', 'H', 'V', 'W', 'Y'],
5: ['K'],
8: ['J', 'X'],
10: ['Q', 'Z']
};
function transform(obj) {
const newScorekey = {};
for (var key in oldScoreKey) {
for (let i = 0; i < oldScoreKey[key].length; i++) {
newScorekey[oldScoreKey[key][i].toLowerCase()] = +key;
}
} return newScorekey;
}
newScorekey = transform(oldScoreKey);
console.log(newScorekey);
推荐阅读
- html - XSLT:for-each div 与部分孩子
- ios - UISegmented Control 具有相同的表格视图和单元格中的 uibutton
- jmeter - JMXmon 动态值处理
- java - 如何将字符串切成碎片并通过蓝牙发送每一个?
- android - 深度链接、Android 应用链接、Firebase 动态链接和应用索引之间的区别
- javascript - 如何确定一个点是否在已解析但未显示的 SVG 文件的 SVG 元素内?
- wordpress - 优先搜索结果以显示标题第一个 wordpress 的匹配结果
- jsx - JSX 字符串字面量
- sql - 仅当变量在元数据库中给出值时才添加过滤器
- c++ - 绘制旋转三角形