看起来这些就是我们所说的并行数组:一个数组的索引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 函数进行函数式编程时才有用。否则,这只是一个过于复杂、容易出错的循环,使用实际循环会更清晰、更容易正确。
在您提出的评论中:
如果我想要它是这样的怎么办? [{ 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]}));