我有这两个数组,我想这样输出:
{
"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
与 Object.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 函数进行函数式编程时才有用。否则,它只是一个过于复杂、容易出错的循环,而使用实际循环会更清晰、更容易正确。
在您提出的评论中:
What If I want it do be like this?
[{ text: 'pt', value: 100, }, { text: 'es', value: 500, }]
?
为此,您需要为数组中的每个条目创建一个对象。您可以通过 map
创建数组,也可以使用 object literal ({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]}));
关于javascript - 如何使用一个数组作为另一个数组的键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64929050/