js:使用reduce()用数组元素填充对象



试图学习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中都有一个密钥。

最新更新