试图学习reduce(),但还不能很好地理解它。也许你们有人可以帮我解决问题。
我有一个带有已定义键和数组的对象。我想使用reduce()用数组值填充对象键。
我的沙箱链接
到目前为止,我尝试过这样的东西:
const myObj = {
first: null,
second: null,
third: null
}
const myArr = [ "abc", "def", "ghi"]
const newObj = myArr.reduce((result, value, index) => {
result[index] = value
return result
}, myObj)
console.log(newObj)
// 0: "abc"
// 1: "def"
// 2: "ghi"
// first: null
// second: null
// third: null
预期结果:
{
first: "abc",
second: "def",
third: "ghi"
}
谢谢你的帮助。
您需要将index
更改为"在CCD_ 2处的对象密钥":
const newObj = myArr.reduce((result, value, index) => {
result[Object.keys(myObj)[index]] = value
return result
}, myObj)
也就是说,zip
+Object.fromEntries
更适合这份工作:
const zip = (...args) => args[0].map((_, i) => args.map(a => a[i]));
const myObj = {
first: null,
second: null,
third: null
}
const myArr = [ "abc", "def", "ghi"]
const result = Object.fromEntries(
zip(
Object.keys(myObj),
myArr
)
)
console.log(result)
运行Object.keys
并重新分配myArr
中每个键的值。
const myObj = {
first: null,
second: null,
third: null
};
const myArr = [ "abc", "def", "ghi"];
Object.keys(myObj).forEach((k,i)=>myObj[k]=myArr[i]);
console.log(myObj);
使用switch
确定将值分配给哪个对象key
:
const myArr = ["abc", "def", "ghi"];
const newObj = myArr.reduce((result, value, index) => {
let key;
switch (index) {
case 0: key = "first"; break;
case 1: key = "second"; break;
case 2: key = "third"; break;
}
result[key] = value;
return result;
}, {});
console.log(newObj);
或者,对于不依赖描述性关键字的更灵活的选项:
const myArr = ["abc", "def", "ghi", "jkl", "mno"];
const newObj = myArr.reduce((result, value, index) => {
result[(index + 1).toString()] = value;
return result;
}, {});
console.log(newObj);
/*
{
"1": "abc",
"2": "def",
"3": "ghi",
"4": "jkl",
"5": "mno"
}
*/
这里有一个SO解,它将整数转换为序数,即1到"0";首先;,2至";第二";,等等——高达";第九十九条";。这为您提供了序号键,并消除了对对象myObj
的需要。通过依赖myObj
来提供密钥名称,您需要预先确定myArr
中有多少个元素,并确保每个元素在myObj
中都有一个密钥。