我有两个相等长度的字符串数组,我想用它们创建一个key:pair对象,比如:
输入:
let words1 = ["foo", "loo", "who"];
let words2 = ["bar", "car", "mar"];
期望输出:
{
foo: "bar",
loo: "car",
who: "mar"
}
我最初是通过做以下事情来完成的:
const wordMap = {};
words1.map((word,n) => {
wordMap[word] = words2[n];
})
然而,我们的门楣正在向";优选破坏";。我似乎不知道如何使用析构函数来实现这一点——鉴于我对析构函数还很陌生,我想我一定是错过了什么。我正在努力寻找一种干净的方法。。。我想答案可能类似于:
{[words1]:[...words2]};
但我想不通。这是一个我也在玩的JSFiddle。如果有办法的话,请告诉我。谢谢
您可以将words1数组转换为数组的words1/words2组合数组,这非常适合通过Object.fromEntries运行。
let words1 = ["foo", "loo", "who"];
let words2 = ["bar", "car", "mar"];
const wordMap = Object.fromEntries(words1.map((w, i) => [w, words2[i]]));
console.log(wordMap);
我似乎不知道如何使用析构函数来实现这一点
林特尔想让你写
({[n]: wordMap[word]} = words2);
而不是
wordMap[word] = words2[n];
这是一个完整的大包——可读性较差,更复杂,甚至不比简单明了的任务更短。忽略这里的规则,它没有意义——或者完全禁用它,也许至少是enforceForRenamedProperties
选项或AssignmentExpression
选项。
尽管James的解决方案有效,但它只适用于ES2019及以后的版本,因为它使用.fromEntries()
。如果你使用前置器,你可能想使用以下(使用析构函数(:
const words1 = ['foo', 'loo', 'who'];
const words2 = ['bar', 'car', 'mar'];
const wordMap = Object.assign(...words1.map((k, i) => ({ [k]: words2[i] })));
console.log(wordMap);
如果第一个数组有更多的字,它会将undefined
指定为其值(见下文(。如果第二个数组有更多的字,它只创建N
键/值对,其中N
等于第一个数组的长度(基本上在数组1没有更多的字后停止(。
const words1 = ['foo', 'loo', 'who', 'zoo'];
const words2 = ['bar', 'car', 'mar'];
const wordMap = Object.assign(...words1.map((k, i) => ({ [k]: words2[i] })));
console.log(wordMap);
至于析构函数,您可以用一个数组重新分配对象的键,用另一个数组来重新分配值。看,马!无迭代!:
let keys = ["foo", "loo", "who"];
let values = ["bar", "car", "mar"];
let zipped = {};
[zipped.foo, zipped.loo, zipped.who] = values;
console.log(zipped);
.reduce()
和Object.assign()
,关键是将累加器作为Object.assign()
的第一个参数和值按索引传递。
let keys = ["foo", "loo", "who"];
let values = ["bar", "car", "mar"];
const zipped = keys
.reduce((object, current, index) =>
Object.assign(object, {[current]: values[index]}), {});
console.log(zipped);
使用Object.hasOwnProperty,这将解决您的问题。
let words1 = ["foo", "loo", "who"];
let words2 = ["bar", "car", "mar"];
let len = words1.length
let newObj = {}
for(let i=0; i<len; i++){
if(!newObj.hasOwnProperty(words1[i])){
newObj[words1[i]] = words2[i]
}
}
console.log(newObj)