javascript - 如何使用一个数组作为另一个数组的键?
问题描述
我有这两个数组,我想像这样输出它:
{
"PT": "100",
"ES": "400",
"FR": "550",
"CH": "200",
"BR": "400",
"DE": "500",
}
我怎样才能做到这一点?可能很简单,但我不知道该怎么做,我也在stackoverflow上搜索过,但没有找到类似的东西..
这是 React 中的一个项目,我不知道这是否重要。谢谢。
解决方案
看起来这些就是我们所说的并行数组:一个数组的索引n处的元素与另一个数组的索引n处的元素相关。
在这种情况下,您可以使用简单的for
循环和括号属性表示法:
const result = {};
for (let index = 0; index < array1.length; ++index) {
result[array1[index]] = array2[index];
}
现场示例:
const array1 = [
"PT",
"ES",
"FR",
"CH",
"BR",
"DE",
];
const array2 = [
100,
400,
550,
200,
400,
500,
];
const result = {};
for (let index = 0; index < array1.length; ++index) {
result[array1[index]] = array2[index];
}
console.log(result);
您也可以使用map
withObject.fromEntries
来创建对象,但它更复杂(虽然更短)并且涉及临时数组对象:
const result = Object.fromEntries(
array1.map((array1value, index) => [array1value, array2[index]])
);
现场示例:
const array1 = [
"PT",
"ES",
"FR",
"CH",
"BR",
"DE",
];
const array2 = [
100,
400,
550,
200,
400,
500,
];
const result = Object.fromEntries(
array1.map((array1value, index) => [array1value, array2[index]])
);
console.log(result);
旁注:在您的输出中,您已将值100
、200
等显示为字符串,但它们是您输入中的数字。如果您希望它们成为字符串,只需随时转换它们,如下所示:
const result = {};
for (let index = 0; index < array1.length; ++index) {
result[array1[index]] = String(array2[index]);
// −−−−−−−−−−−−−−−−−−−−−−−−−^^^^^^^−−−−−−−−−−−−−^
}
现场示例:
const array1 = [
"PT",
"ES",
"FR",
"CH",
"BR",
"DE",
];
const array2 = [
100,
400,
550,
200,
400,
500,
];
const result = {};
for (let index = 0; index < array1.length; ++index) {
result[array1[index]] = String(array2[index]);
}
console.log(result);
您会得到人们的指点reduce
,但reduce
仅当您使用预定义的、可重用的 reducer 函数进行函数式编程时才有用。否则,这只是一个过于复杂、容易出错的循环,使用实际循环会更清晰、更容易正确。
在您问过的评论中:
如果我想要它是这样的怎么办?
[{ text: 'pt', value: 100, }, { text: 'es', value: 500, }]
?
为此,您需要为数组中的每个条目创建一个对象。您可以通过创建数组map
,也可以使用对象文字创建对象({text: "PT", value: 100}
类似,但从数组中获取值):
const result = array1.map((text, index) => ({text: text, value: array2[index]}));
或对属性使用速记属性表示法text
:
const result = array1.map((text, index) => ({text, value: array2[index]}));
现场示例:
const array1 = [
"PT",
"ES",
"FR",
"CH",
"BR",
"DE",
];
const array2 = [
100,
400,
550,
200,
400,
500,
];
const result = array1.map((text, index) => ({text, value: array2[index]}));
console.log(result);
我将这些text
值保留为大写,但如果您想在对象中将它们设为小写,请.toLocaleLowerCase()
在它们上使用:
const result = array1.map((text: text.toLocaleLowerCase(), index) => ({text, value: array2[index]}));