Javascript reduce - 一个参数取了错误的值
Javascript reduce - one argument takes on a wrong value
根据这篇简短的文章,我第一次尝试在 javascript 中使用 reduce:
Understand Javascript Array Reduce in 1 Minute
我有两个相似的对象,一个有一组 20 个键,而另一个有 30 个键,其中 20 个与第一个对象相同。现在,我的目的是使用 reduce 创建一个新对象,它将是第二个对象的副本,但只有这 20 个键(以便我可以比较第一个和第二个对象)。
我正在使用以下代码:
const first = mapOrder(order, contactId);
const third = Object.keys(first).reduce((obj, key) => {
obj[key] = second[key];
return obj;
})
所以我遇到的问题是reduce的obj参数。我会收到以下错误:
TypeError: Cannot create property 'name' on string 'id'
我的 obj 参数似乎被初始化为值为 'name' 的字符串('id' 是我的第一个对象的第一个键)。
所以我所做的,最终给我正确的结果如下:
const first = mapOrder(order, contactId);
const third = Object.keys(first).reduce((obj, key) => {
if(typeof obj == 'string'){
obj = {}
}
obj[key] = second[key];
return obj;
})
谁能向我解释为什么我会遇到这样的问题,以及如何在不让我的代码变得如此丑陋的情况下解决它?也许我遗漏了一些关于 reduce 实际工作原理的信息?
您可以为 Array#reduce
的累加器使用 initialValue(一个新对象)。
initialValue
[Optional] Value to use as the first argument to the first call of the callback
. If no initial value is supplied, the first element in the array will be used. Calling reduce on an empty array without an initial value is an error.
const third = Object.keys(first).reduce((obj, key) => {
obj[key] = second[key];
return obj;
}, {})
// ^^
在你的代码中试试这个
const first = mapOrder(order, contactId);
const third = Object.keys(first).reduce((obj, key) => {
obj[key] = second[key];
return obj;
}, {})
因为语法是
arr.reduce(callback[, initialValue])
查看更多参考资料MDN
根据这篇简短的文章,我第一次尝试在 javascript 中使用 reduce: Understand Javascript Array Reduce in 1 Minute
我有两个相似的对象,一个有一组 20 个键,而另一个有 30 个键,其中 20 个与第一个对象相同。现在,我的目的是使用 reduce 创建一个新对象,它将是第二个对象的副本,但只有这 20 个键(以便我可以比较第一个和第二个对象)。
我正在使用以下代码:
const first = mapOrder(order, contactId);
const third = Object.keys(first).reduce((obj, key) => {
obj[key] = second[key];
return obj;
})
所以我遇到的问题是reduce的obj参数。我会收到以下错误:
TypeError: Cannot create property 'name' on string 'id'
我的 obj 参数似乎被初始化为值为 'name' 的字符串('id' 是我的第一个对象的第一个键)。
所以我所做的,最终给我正确的结果如下:
const first = mapOrder(order, contactId);
const third = Object.keys(first).reduce((obj, key) => {
if(typeof obj == 'string'){
obj = {}
}
obj[key] = second[key];
return obj;
})
谁能向我解释为什么我会遇到这样的问题,以及如何在不让我的代码变得如此丑陋的情况下解决它?也许我遗漏了一些关于 reduce 实际工作原理的信息?
您可以为 Array#reduce
的累加器使用 initialValue(一个新对象)。
initialValue
[Optional] Value to use as the first argument to the first call of the
callback
. If no initial value is supplied, the first element in the array will be used. Calling reduce on an empty array without an initial value is an error.
const third = Object.keys(first).reduce((obj, key) => {
obj[key] = second[key];
return obj;
}, {})
// ^^
在你的代码中试试这个
const first = mapOrder(order, contactId);
const third = Object.keys(first).reduce((obj, key) => {
obj[key] = second[key];
return obj;
}, {})
因为语法是
arr.reduce(callback[, initialValue])
查看更多参考资料MDN